3

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?

allo
  • 3,955
  • 8
  • 40
  • 71
David542
  • 104,438
  • 178
  • 489
  • 842
  • Can you just write to a file? A coworker once pointed this out to me, and for my situation that was enough. Certainly simpler and avoids a dependency which can break easily. EDIT: I initially misunderstood your question, thinking logging wasn't working for you. As long as logging is working, your question is valid. I do not know the answer offhand, unfortunately – Nathan majicvr.com Aug 02 '18 at 21:59

1 Answers1

6

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.

hoefling
  • 59,418
  • 12
  • 147
  • 194
  • 1
    AFAICT, `basicConfig` by default outputs in STDERR, not STDOUT like the OP asked. you need to add `stream=sys.stdout` to the basicConfig – Hilikus Oct 25 '21 at 17:52
  • @Hilikus you're absolutely right, thanks for pointing that out! – hoefling Oct 26 '21 at 14:29