什么是Python的默认日志记录格式化程序?

Tre*_*ent 34 python logging

我正在尝试破译日志中包含的信息(日志记录设置使用默认格式化程序).该文件规定:

对记录进行格式化 - 如果设置了格式化程序,请使用它.否则,请使用模块的默认格式化程序.

但是,我找不到任何实际说明这种默认格式的引用.

rh0*_*ium 47

默认格式位于此处:

BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"  
Run Code Online (Sandbox Code Playgroud)

格式的代码会告诉你如何定义它.这是一个关于如何自定义它的示例.

import sys
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
    datefmt="%H:%M:%S",
    stream=sys.stdout)

logging.info("HEY")
Run Code Online (Sandbox Code Playgroud)

结果如下:

[26/May/2013 06:41:40] INFO [root.<module>:1] HEY
Run Code Online (Sandbox Code Playgroud)

  • 我想我有点晚了,但是对于后来的几代人,你可以在[python的源代码在这里](https://github.com/python/cpython/blob/main/Lib/logging/__init__.py)查找对于 basicConfig 方法,如果方法中不存在格式键,则可以看到 fs = kwargs.pop("format", _STYLES[style][1]) 中默认为 _STYLES[style][1]。如果 basicConfig 方法中不存在,则 style 默认为“%”。这给了我们格式 _STYLE["%"][1] = BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"。您也可以从文档中推断。 (3认同)
  • 在您的示例中未定义`log`。可能应该称为“日志记录”。 (2认同)

Dav*_*ger 6

@rh0dium's and @Blender's answers contradict each other but they're both correct... just incomplete.

As of Python 3.10:

  • If you create a handler without specifying a formatter, the default format is "%(message)s".
  • If you call logging.basicConfig it sets up a handler on the root logger with a formatter that defaults to "%(levelname)s:%(name)s:%(message)s".
    • Note that logging.info, logging.warning etc will automatically call logging.basicConfig() if you haven't called it already.
    • But calling the root logger directly (like logging.getLogger().info(...)) won't call logging.basicConfig().

So the actual behaviour depends on whether you've ever called logging.basicConfig or logging.info/logging.warning/etc.

$ python3
Python 3.10.4 (main, Apr  2 2022, 09:04:19) [GCC 11.2.0] on linux
>>> import logging
>>> root = logging.getLogger()
>>> root.warning("W")
W
>>> logging.warning("W")
WARNING:root:W
>>> root.warning("W")
WARNING:root:W
>>> mylogger = logging.getLogger("mylogger")
>>> mylogger.addHandler(logging.StreamHandler())
>>> mylogger.propagate = False
>>> mylogger.warning("W")
W
Run Code Online (Sandbox Code Playgroud)


awh*_*han 5

import logging
print(logging.BASIC_FORMAT)
Run Code Online (Sandbox Code Playgroud)

旧线程,但这首先出现在我的Google搜索结果中以查询“ python logging default format”,因此我认为我应该添加答案。

也有一些评论询问人们如何独自发现这一点。这是很自然的事情:

import logging
print(dir(logging))
Run Code Online (Sandbox Code Playgroud)

BASIC_FORMAT在其中,实际上,对于我而言,它是结果中的第一项。