Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial String Formatting in Python Logging Formatters

I'm looking for a way to perform partial string formatting in Python logging formatters.

When trying to define a formatter the following way:

formatter = logging.Formatter('[num-%d] %(levelname)s %(message)s' % (num,))

I will get a TypeError with "format requires a mapping" which is reasonable as the interpreter couldn't find 'levelname' and 'message'.

Of course, I would like both 'levelname' and 'message' to remain un-formatted for the logging framework to handle.

As I see, there are two other ways of addressing the issue:

  1. format = '[num-' + str(num) + '] %(levelname)s %(message)s' % (num,)
  2. format = '[num-%(num)d] %(levelname)s %(message)s' % dict(num=num, levelname='%(levelname)s', message='%(message)s')

However, I find both solutions somewhat ugly, and I believe there must be a better way to format only part of the string - either in Python, or using in the python builtin logging framework.

Any Ideas?

like image 898
amito Avatar asked Aug 24 '11 13:08

amito


1 Answers

Try this:

formatter = logging.Formatter('[num-%d] %%(levelname)s %%(message)s' % (num,))

You have to give the Formatter method your string with %(...)s fields. The %% will interpret into % and therefore can be used.

like image 170
eumiro Avatar answered Sep 26 '22 01:09

eumiro