Almost every time I try to use the logging module in Python, I end up mucking it up and then needing to refer to the documentation.

Here’s what a typical script looks like:

import logging
logging.info("Hello world")

Of course, when you run this, you get no output. You need to make a call to logging.basicConfig() first:

import logging
logging.basicConfig(level=logging.INFO)
logging.info("Hello world")

This time, I do actually get some output:

INFO:root:Hello world

This is ugly though. The second thing I always forget is that you need to pass the format parameter to it. All together:

import logging
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s - %(levelname)s - %(message)s")
logging.info("Hello world")

This finally produces some nice output:

2009-08-19 14:18:37,161 - INFO - Hello world