我想将所有日志附加到python中的一个文件中

时间:2019-12-19 08:46:57

标签: python

我有用于在当前目录上写入日志的代码。它工作正常,并且将来自不同类的所有日志写入一个文件。

现在我想在特定目录(例如:日志目录)中编写代码

class PyLog():

    def create_log_handler(self, module, log_file, log_level=None):

        logger = logging.getLogger(module)
        if not log_level is None:
            logger.setLevel(log_level)
        if not getattr(logger, 'handler_set', None):
            fileh = logging.FileHandler(log_file)
            fh_format = logging.Formatter('%(asctime)s -  %(name)s:%(lineno)d - %(levelname)s - %(message)s')
            fileh.setFormatter(fh_format)
            logger.addHandler(fileh)
            if not log_level is None:
                fileh.setLevel(log_level)
            logger.handler_set = True
            setattr(PyLog, 'log_file', log_file)
            setattr(PyLog, 'logger', logger)
        return logger

    def get_logger(self, module, log_file, log_level=None, set_attr=False):


        logger = logging.getLogger(module)

        if not log_level is None:
            logger.setLevel(log_level)

        if not getattr(logger, 'handler_set', None):
            fileh = logging.FileHandler(log_file)
            fh_format = logging.Formatter('%(asctime)s -  %(name)s:%(lineno)d - %(levelname)s - %(message)s')
            fileh.setFormatter(fh_format)
            logger.addHandler(fileh)

            if not log_level is None:
                fileh.setLevel(log_level)

            logger.handler_set = True

            if set_attr:
                setattr(PyLog, 'log_file', log_file)
                setattr(PyLog, 'logger', logger)
        return logger

    @staticmethod
    def write_log(logger_method, log_msg):
        log_msg = str(log_msg)
        print ("%s: %s"%(logger_method , log_msg))
        logger_method(log_msg)


    @staticmethod
    def getTimeStamp():
        return datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S')

我正在像下面这样的其他xyz类中创建对象

   try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                     getattr(PyLog, "log_file"), logging.INFO)
   except AttributeError:
       logger = PyLog().get_logger(self.__class__.__name__,
                                     os.path.join(os.getcwd(),
                                                  "%s.log" % self.__class__.__name__),
                                     logging.INFO)

与abc类相同

    try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                        getattr(PyLog, "log_file"), logging.INFO)
      except AttributeError:
          logger = PyLog().get_logger(self.__class__.__name__,
                                        os.path.join(os.getcwd(),
                                                     "%s.log" % self.__class__.__name__),
                                        logging.INFO)

用于在当前工作目录的xyz日志文件中写入xyz类和abc类的日志。

现在,我想将所有日志写到Logs文件夹中,因此我更改了以下内容,但它开始为xyz.log,abc.log之类的每个类编写创建日志文件。

       try:
           logger = PyLog().get_logger(self.__class__.__name__,
                                       getattr(PyLog, "log_file"), logging.INFO)
       except AttributeError:
           if not os.path.exists(os.getcwd() + "\\Logs"):
               os.mkdir(os.getcwd() + "\\Logs")

           log_dir = os.getcwd() + "\\Logs"
           logger = PyLog().get_logger(self.__class__.__name__,
                                       os.path.join(log_dir,
                                                    "%s.log" % self.__class__.__name__),
                                       logging.INFO)

请有人帮我解决这个问题。它应该将所有日志写入一个文件。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我们必须设置set_attr = True,然后将所有日志写入一个文件。

get_logger(自身,模块,log_file,log_level =无,set_attr = True)

例如:

   try:
       logger = PyLog().get_logger(self.__class__.__name__,
                                   getattr(PyLog, "log_file"), logging.INFO)
   except AttributeError:
       if not os.path.exists(os.getcwd() + "\\Logs"):
           os.mkdir(os.getcwd() + "\\Logs")

       log_dir = os.getcwd() + "\\Logs"
       logger = PyLog().get_logger(self.__class__.__name__,
                                   os.path.join(log_dir,
                                                "%s.log" % self.__class__.__name__),
                                   logging.INFO, True)