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:
format = '[num-' + str(num) + '] %(levelname)s %(message)s' % (num,)
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With