python 2.7-设置2个记录器
作者:互联网
我正在尝试设置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 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.
换句话说,它只会在第一次被调用时才起作用.
如果我正确理解的话,此功能仅是“最后手段”配置.
您应该改为根据“自我”引用而不是全局基本配置来配置每个记录器.
我为每个模块级记录器使用的基本模式是(请注意import语句!):
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__)
我确定我是从某处复制的…
标签:logging,python-2-7,python-2-x,python 来源: https://codeday.me/bug/20191119/2039663.html