本文介绍了设置python日志到stdout的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要设置一个基本的记录器以在cron作业中打印输出:

I have the following to set up a basic logger to print output in a cron job:

import logging
log=logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logging.StreamHandler())
log.info('hi')

这是最简单的方法吗?还是有更好的方法?

Is this the most straightforward way to do this, or is there a better method?

推荐答案

如果只需要将消息打印到标准输出,则 logging.basicConfig 是列出的配置的便捷快捷方式.它将创建一个 StreamHandler ,将默认的 Formatter 附加到该代码,并将该处理程序附加到根记录器.

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.

这篇关于设置python日志到stdout的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:44