Simplest Way To Set Up Python Logging To Stdout
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
Solution 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, stream=sys.stdout)
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.
Post a Comment for "Simplest Way To Set Up Python Logging To Stdout"