在新的日志记录处理程序中包含以前记录的事件

时间:2012-10-15 12:06:11

标签: python logging

请考虑以下示例:

import logging
#create a logger object:
logger = logging.getLogger("MyLogger")
#define a logging handler for the standard output:
stdoutHandler = logging.StreamHandler(sys.stdout)
logger.addHandler(stdoutHandler)
#...
#initialization code with several logging events (for example, loading a configuration file to a 'conf' object)
#...
logger.info("Log event 1")
#after configuration is loaded, a new logging handler is defined for a log file:
fileHandler = logging.FileHandler(conf.get("main","log_file"),'w')
logger.addHandler(fileHandler)
logger.info("Log event 2")

使用此示例,“日志事件1”不会出现在日志文件中(仅在stdout中)。 在“Log event 1”之后,日志文件不可避免地被初始化(因为它取决于配置)。

我的问题是:
如何在新的日志处理程序(例如示例中的文件处理程序)中包含以前记录的事件(例如“日志事件1”)?

1 个答案:

答案 0 :(得分:4)

我对这个问题的解决方案:

定义MemoryHandler以处理FileHandler定义之前的所有事件 定义FileHandler后,将其设置为MemoryHandler的刷新目标并刷新它。

import logging
import logging.handlers
#create a logger object:
logger = logging.getLogger("MyLogger")
#define a memory handler:
memHandler = logging.handlers.MemoryHandler(capacity = 1024*10)
logger.addHandler(memHandler)
#...
#initialization code with several logging events (for example, loading a configuration file to a 'conf' object)
#everything is logged by the memory handler
#...

#after configuration is loaded, a new logging handler is defined for a log file:
fileHandler = logging.FileHandler(conf.get("main","log_file"),'w')
#flush the memory handler into the new file handler:
memHandler.setTarget(fileHandler)
memHandler.flush()
memHandler.close()
logger.removeHandler(memHandler)
logger.addHandler(fileHandler)

这对我有用,所以我接受这是正确的答案,直到出现更优雅的答案。