0

When I write a message to a Python logger, and the message has parameters, I now write it like this:

logger.info("Person %s cuts at %f.", person.name, location)

This is the old way of string-formatting; the new way would be:

logger.info("Person {} cuts at {}.", person.name, location)

but this raises an error. I could convert the message into a single string like so:

logger.info("Person {} cuts at {}.".format(person.name, location))

However, in this case the string is generated even when the log message should not be displayed, e.g. when the logging level is WARNING. This is wasteful.

My question is: how can I write a log message that does not automatically expand its parameters, while using the new syntax for string formatting?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • logger.info("Person {name} cuts at {location}.".format(name=person.name,location=location)) you can try this – nithin Nov 26 '19 at 10:48
  • @nithin this still has the same efficiency problem: generates the string even when the logger is in WARNING level. – Erel Segal-Halevi Nov 26 '19 at 11:01
  • Why exactly do you want to do this? What is the issue with using the old-style syntax when it's still the suggested way? If you really want to persist there are some considerations [here](https://stackoverflow.com/questions/13131400/logging-variable-data-with-new-format-string) – PyPingu Nov 26 '19 at 11:03
  • @PyPingu for consistency: I use the new syntax everywhere throughout my code, and it is strange to use a different syntax just for logging. – Erel Segal-Halevi Nov 26 '19 at 11:14
  • It seems odd to me to add complexity for the sake of a little string formatting consistency (which personally I don't see as all that inconsistent - logs simply have their own rules imo) but if you really want to then I think that what you need can be found in the docs [here](https://docs.python.org/3/howto/logging-cookbook.html#using-custom-message-objects) – PyPingu Nov 26 '19 at 11:41

0 Answers0