且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

设置python日志到stdout的最简单方法

更新时间:2022-04-05 08:50:07

如果只需要将消息打印到标准输出,则

If you just need to print the messages to the stdout, then logging.basicConfig is a handy shortcut for the configuration you listed. It will create a StreamHandler, attach the default Formatter to it and attach the handler to the root logger.

import logging

logging.basicConfig(level=logging.DEBUG)
logging.getLogger().info('hi')

查看文档以了解更多配置可能性;例如,

Check out the docs for more configuration possibilities; for example,

logging.basicConfig(filename='some.log', level=logging.DEBUG)

将配置写入文件 some.log 而不是 stdout.

will configure writing to file some.log instead of stdout.

请注意,如果已经配置了记录器,则 logging.basicConfig 不会做任何事情(这意味着已经在根记录器上附加了处理程序).所以这段代码:

Note that logging.basicConfig won't do a thing if the logger is already configured (meaning that there are handlers attached to the root logger already). So this code:

import logging

logging.getLogger().addHandler(logging.FileHandler(filename='some.log'))
logging.basicConfig(level=logging.DEBUG)

将不再将日志记录配置为标准输出;您将必须自己做.

will not configure logging to stdout anymore; you will have to do it yourself.