python 2.7 - 设置 2 个记录器

python 2.7 - setting up 2 loggers

我正在尝试设置 2 个记录器,不幸的是其中一个没有写入文件,这是我的代码片段:

LOG_FILENAME = 'test.log'
LOG_FILENAME2 = 'test2.log'
error_counter = 0
error_logger = CustomLogger(LOG_FILENAME2, 'w', '%(asctime)s - %(levelname)s -  %(message)s',
                            '%d/%m/%Y %H:%M:%S')
error_logger.set_level('info')
error_logger.basic_config()
print "This is the first logger: {0}".format(error_logger.get_file_path)
error_logger.log_message("This is a test message of the first instance")

warning_logger = CustomLogger(LOG_FILENAME, 'w', '%(asctime)s - %(levelname)s -  %(message)s',
                              '%d/%m/%Y %H:%M:%S')

warning_logger.set_level('warning')
warning_logger.basic_config()
print "This is the the second logger: {0} ".format(warning_logger.get_file_path)
warning_logger.log_message("this is a test message of the second instance")

这是我创建的自定义 class:

class CustomLogger(object):

    LEVELS = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
              'critical': logging.CRITICAL}

    def __init__(self, i_file_path=None, i_filemode=None, i_format=None, i_date_format=None, i_log_level=None):

        self.__file_path = i_file_path
        self.__filemode = i_filemode
        self.__format = i_format
        self.__date_format = i_date_format
        self.__log_level = i_log_level

def basic_config(self):
        logging.basicConfig(
            filename=self.__file_path,
            filemode=self.__filemode,
            format=self.__format,
            datefmt=self.__date_format,
            level=self.__log_level
            )
def log_message(self, i_message):
        try:
            if None in (self.__file_path, self.__log_level, self.__filemode, self.__date_format, self.__format):
                raise ErrorLoggerPropertiesRequiredException()
        except ErrorLoggerPropertiesRequiredException as e:
            print "{0}".format(e.message)
        else:
            curr_logger = logging.getLogger(self.__file_path)
            print "writing to log {0}".format(i_message)
            curr_logger.log(self.__log_level, i_message)

它只创建并写入第一个记录器,我已经尝试了很多我在 Python Documentation 上看到的东西,还有另一个 属性 叫做 disable_existing_loggers,默认情况下是 True,我已尝试使用 logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=False) 访问此 属性,但似乎没有这样的方法。

我相信你正在运行遇到一个我已经运行多次遇到的问题:

logging.basicConfig()

正在调用模块级配置,并且根据文档:

This function does nothing if the root logger already has handlers configured for it.

换句话说,它只会在第一次调用时生效。 如果我理解正确,此功能仅作为 "last resort" 配置。

您应该改为根据 "self" 参考配置每个记录器,而不是全局基本配置...

我用于每个模块级记录器的基本模式是(注意导入语句!):

import logging.config
try:
       logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
except Exception as e:
    # try to set up a default logger
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s:%(name)s:%(lineno)d %(levelname)s : %(message)s")
main_logger = logging.getLogger(__name__)

我确定我是从某处复制的...