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?

5
  • logger.info("Person {name} cuts at {location}.".format(name=person.name,location=location)) you can try this Commented Nov 26, 2019 at 10:48
  • @nithin this still has the same efficiency problem: generates the string even when the logger is in WARNING level. Commented Nov 26, 2019 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 Commented Nov 26, 2019 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. Commented Nov 26, 2019 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 Commented Nov 26, 2019 at 11:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.