5

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?

asked Aug 24, 2011 at 13:06
0

1 Answer 1

5

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.

answered Aug 24, 2011 at 13:09
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.