我有一个LOG_SETTINGS dict,如下所示:
LOG_SETTINGS = { 'version': 1,'handlers': { 'console': { 'class': 'logging.StreamHandler','level': 'INFO','formatter': 'detailed','stream': 'ext://sys.stdout',},'file': { 'class': 'logging.handlers.RotatingFileHandler','filename': '/tmp/junk.log','mode': 'a','maxBytes': 10485760,'backupCount': 5,'formatters': { 'detailed': { 'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \ '%(levelname)-8s %(message)s','email': { 'format': 'Timestamp: %(asctime)s\nModule: %(module)s\n' \ 'Line: %(lineno)d\nMessage: %(message)s','loggers': { 'extensive': { 'level':'DEBUG','handlers': ['file',] },} }
在我的代码中,我执行以下操作:
logging.config.dictConfig(LOG_SETTINGS) logger = logging.getLogger('extensive') logger.info("This is from Runner {0}".format(self.default_name)) logger2 = logging.getLogger('extensive') logfile = logging.FileHandler("test.log") logger2.addHandler(logfile) logger2.info("This is from Runner {0} to the new file.".format(self.default_name))
但输出仍然写入LOG_SETTINGS中定义的原始日志文件.我正在寻找的是有能力说:logger2.replaceHandler(logfile)而不是addHandler.
有没有办法做到这一点?
解决方法
首先,清空记录器处理程序logger.handlers = []然后添加另一个处理程序.
logger2 = logging.getLogger('extensive') logfile = logging.FileHandler("test.log") logger2.handlers = [] logger2.addHandler(logfile)