日志层级与根日志器?
在我代码的某个地方,有这么一段:
logger = logging.getLogger('debug0.x')
我理解的是,这段代码应该只在我之前做过类似的事情时才会有反应:
logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0')
注意,name被定义为debug0。然而,我发现如果我这样做:
logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG)
没有name这个关键词时,上面定义的debug0.x日志记录器会反应,并且会写入日志文件。我原本以为它只会在第一种情况下有反应,也就是当日志记录器被命名的时候。
我感到很困惑。
2 个回答
18
如果你查看一下代码或者文档:
>>> print logging.basicConfig.__doc__
Do basic configuration for the logging system.
This function does nothing if the root logger already has handlers
configured. ...............
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
filename Specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified
(if filemode is unspecified, it defaults to 'a').
format Use the specified format string for the handler.
datefmt Use the specified date/time format.
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with 'filename' - if both
are present, 'stream' is ignored.
logging.basicConfig根本不使用name这个参数。它是用来初始化根日志记录器的。而getLogger方法是需要一个“name”参数的。
>>> print logging.getLogger.__doc__
Return a logger with the specified name, creating it if necessary.
If no name is specified, return the root logger.
131
Python的logging
模块把日志记录器(logger)组织成一个层级结构。所有的日志记录器都是根日志记录器的“后代”。每个日志记录器都会把日志信息传递给它的父级记录器。
新的日志记录器是通过getLogger()
这个函数来创建的。比如,调用logging.getLogger('debug0.x')
会创建一个名为x
的日志记录器,它是debug0
的子记录器,而debug0
又是根日志记录器的子记录器。当你向这个日志记录器发送日志信息时,它会把信息传递给它的父记录器,然后父记录器再把信息传递给根记录器。你通过basicConfig()
函数配置了根记录器,让它把日志信息记录到一个文件里,所以最终你的信息会被记录到那个文件中。