在没有格式化的情况下,额外记录到Std.out

2024-04-26 22:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,使用

import logging
logging.basicConfig(filename="logname",
                    filemode='a',
                    format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
                    datefmt='%D %H:%M:%S',
                    level=logging.DEBUG)

logging.getLogger().addHandler(logging.StreamHandler())
logging.info("=================================================")
logging.info("starting execution")

我能够在日志文件中很好地记录格式:

03/30/18 12:52:08,231 root INFO =================================================
03/30/18 12:52:08,232 root INFO starting execution

不幸的是,对于控制台,格式设置没有得到遵守:

Connected to pydev debugger (build 173.4674.37)
=================================================
starting execution

我必须写些什么才能使控制台输出的格式也成为可能


Tags: importinfoformatlogging格式rootfilenameexecution
1条回答
网友
1楼 · 发布于 2024-04-26 22:13:43

python文档中的这个示例看起来就是为了实现这个技巧https://docs.python.org/2/howto/logging-cookbook.html#logging-to-multiple-destinations

import logging
logging.basicConfig(filename="logname",
                    filemode='a',
                    format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
                    datefmt='%D %H:%M:%S',
                    level=logging.DEBUG)

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

logging.info("=================================================")
logging.info("starting execution")

给出以下控制台输出

2018-03-30 19:15:00,940,940 root INFO =================================================
2018-03-30 19:15:07,768,768 root INFO starting execution

相关问题 更多 >