Python logger格式化未格式化字符串 [英] Python logger formatting is not formatting the string
问题描述
以下是mylogger.py
的内容:
def get_logger(name='my_super_logger'):
log = logging.getLogger(name)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
if not len(log.handlers):
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
log.addHandler(ch)
# print(id(log))
return log
以及以下是myscript.py
的内容:
from mylogger import get_logger
_logger = get_logger()
_logger.info('trying info')
_logger.debug('trying debug')
但是我面临两个问题.它两次打印日志,并且每次格式化程序都不起作用:
However I am facing two issues. It prints the logs twice and formatter is not working everytime:
09/18/2015 09:59:54 PM my_super_logger trying info
INFO:my_super_logger:trying info
09/18/2015 09:59:54 PM my_super_logger trying debug
DEBUG:my_super_logger:trying debug
我的get_logger
代码到底有什么问题?
What exactly is the issue with my get_logger
code?
我需要自定义格式.但是我发现,如果不添加处理程序,则无法添加formatter
.这就是为什么我添加了StreamHandler
的原因.在答案中提到了if
阻止的原因.否则,我将打印出重复的日志消息.
I need a custom formatting. However I found out that without adding a handler I cannot add a formatter
. So that's why I have added StreamHandler
. And the reason for if
block is mentioned in this answer. Without that, I would get duplicate log messages printed.
推荐答案
root记录程序也正在发出该消息.通过以下方式停止传播到根部:
The root logger is also emitting the message. Stop propagation up to the root with:
log.propagate = False
如果您要格式化 all 日志输出(因此消息将传播到记录器),请为根记录器设置格式化程序.
If you wanted to format all log output (so messages propagated up to the logger), set the formatter for the root logger.
您可以通过 logging.basicConfig()
调用来执行此操作如果尚未将任何内容发送到记录器,或者通过遍历根记录器的logger.handlers
列表;如果愿意,您可以选择任何StreamHandlers
:
You can do so with a logging.basicConfig()
call provided nothing has yet been sent to the loggers, or by looping over the logger.handlers
list of the root logger; you could pick out any StreamHandlers
if you so wish:
root_logger = logging.getLogger() # no name
for handler in root_logger.handlers:
if isinstance(handler, logging.Streamhandler):
handler.setFormatter(formatter)
这篇关于Python logger格式化未格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!