记录层次结构与根记录器?

rec*_*ner 37 python logging

在我的代码的某处,我有类似的东西:

logger = logging.getLogger('debug0.x')
Run Code Online (Sandbox Code Playgroud)

我理解它的方式,这应该在我以前做过类似的事情时才会响应:

logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0')
Run Code Online (Sandbox Code Playgroud)

请注意,名称已定义为debug0.但是,我发现如果这样做

logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)

如果没有name关键字,则上面定义的debug0.x logger会做出反应,并写入日志文件.我认为它只会在第一种情况下做出反应,当记录器被命名时.

我糊涂了.

Sve*_*ach 77

Python logging模块在层次结构中组织记录器.所有记录器都是根记录器的后代.每个记录器都将日志消息传递给其父级.

使用该getLogger()功能创建新的记录器.函数调用logging.getLogger('debug0.x')创建一个记录器x,该记录器debug0本身是根记录器的子节点.当记录到此记录器时,它会将消息传递给其父记录,并且其父记录将消息传递给根记录器.您basicConfig()已将根记录器配置为通过该功能记录到文件,因此您的消息将在那里结束.

  • @Garret Python中最常用的方法是在每个模块的顶部使用`logger = logging.getLogger(__ name __)`.变量`__name__`包含当前模块的虚线名称. (7认同)

pyf*_*unc 13

如果您查看代码或文档:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

logging.basicConfig根本不使用name参数.它初始化根记录器.而getLogger采用"名称"参数

>>> print logging.getLogger.__doc__

    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
Run Code Online (Sandbox Code Playgroud)