[英]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 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文檔中看到的東西,還有另一個名為disable_existing_loggers
屬性,默認情況下是True,我嘗試使用logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=False)
訪問此屬性logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=False)
,但似乎沒有這樣的方法。
我相信你遇到了我遇到過多次的問題:
logging.basicConfig()
正在調用模塊級配置,並根據文檔:
如果根記錄器已經為其配置了處理程序,則此函數不執行任何操作。
換句話說,它只會在第一次調用時產生影響。 如果我理解正確的話,這個函數只是作為“最后的手段”配置。
您應該根據“自我”引用配置每個記錄器,而不是全局基本配置...
我用於每個模塊級記錄器的基本模式是(注意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__)
我相信我是從某個地方復制過的......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.