Simplest way to set up python logging to stdout

邮差的信 提交于 2021-02-10 06:20:25

问题


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?


回答1:


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)

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

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.



来源:https://stackoverflow.com/questions/51662409/simplest-way-to-set-up-python-logging-to-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!