Formatting python log messages

Tags: python

I see three conflicting styles of log formatting in most of the code I come across. Basically:

import logging

logging = logging.getLogger(__name__)

logger.info("%s went %s wrong", 42, 'very')
logger.info("{} went {} wrong".format(42, 'very'))
logger.info("%s went %s wrong" % (42, 'very'))

I looked at the official PEP 282 and at the official docs.

With the help of someone’s stackoverflow question I think I understand it now.

  • Use the first version of the three examples. So:

    • The actual log message with the old, well-known %s (and %d, %f, etc) string formatting indicators.

    • As many extra arguments as you have %s-thingies in your string.

  • Don’t use the second and third example, as both of them format the string before it gets passed to the logger. So even if the log message doesn’t need to be actually logged somewhere, the full string gets created.

    The first example only gets passed a string and some extra arguments and only turns it into a real full string for in your logfile if it actually gets logged. So if you only display WARN level and higher, your DEBUG messages don’t need to be calculated.

  • There is no easy way to use the first example with {} instead of %s.

So: use the logger.info("%s went %s wrong", 42, 'very') form.

(Unless someone corrects me, of course)

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):