【发布时间】:2026-01-31 13:15:01
【问题描述】:
我正在尝试破译我的日志中包含的信息(日志记录设置使用默认格式化程序)。 documentation 声明:
对记录进行格式化 - 如果设置了格式化程序,请使用它。否则,使用模块的默认格式化程序。
但是,我找不到任何实际说明此默认格式的参考资料。
【问题讨论】:
-
文档似乎应该表明这一点。
我正在尝试破译我的日志中包含的信息(日志记录设置使用默认格式化程序)。 documentation 声明:
对记录进行格式化 - 如果设置了格式化程序,请使用它。否则,使用模块的默认格式化程序。
但是,我找不到任何实际说明此默认格式的参考资料。
【问题讨论】:
默认格式位于here,即:
BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
Format 代码将告诉您如何自定义它。这是一个关于如何自定义它的示例。
import sys
import logging
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
datefmt="%d/%b/%Y %H:%M:%S",
stream=sys.stdout)
logging.info("HEY")
结果:
[26/May/2013 06:41:40] INFO [root.<module>:1] HEY
【讨论】:
import logging
print(logging.BASIC_FORMAT)
旧线程,但这首先出现在我的谷歌搜索结果中,查询“python logging default format”,所以我想我应该添加我的答案。
还有一些 cmets 询问一个人是如何自己发现这一点的。这是很自然的事情:
import logging
print(dir(logging))
BASIC_FORMAT 在那里,实际上它是我的情况下结果中的第一个条目。
【讨论】:
在logging/__init__.py的源码中:
_defaultFormatter = Formatter()
默认的格式化字符串是%(message)s,它也在源代码中:
if fmt:
self._fmt = fmt
else:
self._fmt = "%(message)s"
【讨论】:
这里是一个高级日志记录的例子:-
import logging
class logger_con():
def log_test(self):
"""
:create logger
:set logger level
:create console handler
:add formatter to console handler
:add console handler to logger
:add logging massage
:return:
"""
#create logger and set level
logger=logging.getLogger(logger_con.__name__)
logger.setLevel(logging.INFO)
#create console handler(we are using steamHandler which is only used to display log in console)
con_handler=logging.StreamHandler()
con_handler.setLevel(logging.INFO)
#create formatter and add formatter to con_handler
formatter=logging.Formatter('%(asctime)s : %(message)s : %(levelname)s -%(name)s',datefmt='%d%m%Y %I:%M:%S %p')
con_handler.setFormatter(formatter)
#add console handler to logger
logger.addHandler(con_handler)
logger.debug('Program debugging')
logger.info('massage conatain information')
logger.warning('warning message')
logger.error('massage contains error')
logger.critical('critical massages')
【讨论】:
默认好像是%(levelname)s:%(name)s:%(message)s
import logging
logging.error("Some error")
print "fmt: " , logging.root.handlers[0].formatter._fmt
# ERROR:root:Some error
# fmt: %(levelname)s:%(name)s:%(message)s
【讨论】: