Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Logger string formatting

As I understand it,

 'hello {0}'.format("world")

is slower than:

"hello %s" % "world"

My question is, how does logger format the strings when passed like so:

logger.debug("hello %s", "world")

And assuming the logs will never be turned off would it be better to do:

logger.debug("hello %s" % "world")
like image 555
peu ping Avatar asked Jul 21 '12 04:07

peu ping


2 Answers

Don't forget that if you end up using a logging aggregation service such as Sentry, then all the calls to:

logger.error("hello %s", planet)

will be grouped together as multiple occurrences of the same error, while all the calls to:

logger.error("hello %s" % (planet,))

will be listed as many different errors, each of which happened once. This can make it hard to triage which errors are actually frequently occurring.

This grouping behaviour is based on the value of the first parameter to the logging call. In the first example, they are all identical, whereas in the second, they all depend on the value of 'planet'.

So it's important not to use the '%' or .format operators on the strings you pass to logging. Let the logging call do it for you.

like image 90
Jonathan Hartley Avatar answered Oct 13 '22 00:10

Jonathan Hartley


logger.debug(msg, arg1, arg2) does internally: msg = msg % (arg1, arg2) as documented so no surprise here.

logger.debug(msg, arg1, arg2, ...) might look tidier than logger.debug(msg % (arg1, arg2, ...)) and doesn't perform formatting prematurely.

like image 37
jfs Avatar answered Oct 12 '22 23:10

jfs