4

请考虑以下示例:

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”不会出现在日志文件中(仅在标准输出中)。日志文件不可避免地在“日志事件 1”之后初始化(因为它取决于配置)。

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

4

1 回答 1

4

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

定义一个MemoryHandler来处理定义之前的所有事件FileHandler。定义
时,将其设置为的刷新目标并刷新它。 FileHandlerMemoryHandler

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)

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

于 2012-10-15T12:54:51.343 回答