Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use modern string formatting options with Python's logging module?

Tags:

python

logging

The Python logging tutorial says that the newer ways of formatting are beyond the scope of the tutorial, without mentioning where to learn about it.

I would appreciate any examples or link to documentation that allow me to use .format() style message formatting in logging calls such as debug(), info(), etc.

like image 922
Terrence Brannon Avatar asked Nov 21 '12 19:11

Terrence Brannon


People also ask

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

What does logging module do in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.


1 Answers

Recently, I was looking for that too. I think I got pointed to the solution here on SO, but I only have the final url at hand. This is what I do:

# http://plumberjack.blogspot.de/2010/10/supporting-alternative-formatting.html
class BraceMessage(object):
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

_F = BraceMessage

Can be used like this:

logger.debug(_F("foo {0} {quux}", bar, quux=baz))

The formatting will only take place in the very moment the message is evaluated, so you don't lose lots of performance if a log level is disabled. The author of that snippet above made this (and some other utilities) available as a package: logutils.

like image 164
Jonas Schäfer Avatar answered Sep 29 '22 19:09

Jonas Schäfer