Patrick
Patrick

Reputation: 1323

How to avoid string format when set logging level to high level

In my program, there are lots of logging and it seems there is overhead to format a string inside a debug log, even when I set log level to INFO. Is there any way to avoid the overhead?

logger.debug("result is %s " % xxxxx); 

Upvotes: 1

Views: 179

Answers (1)

Amitai Irron
Amitai Irron

Reputation: 2065

The logger is actually equipped to deal with this:

logging.debug(msg, *args, **kwargs)

Logs a message with level DEBUG on the root logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)

This indicates that if you use a string format in msg that is compatible with the format method, the logger will apply the format method on msg and the rest of its arguments (both positional and named). format will not be called if the message does not need to be emitted (e.g., when you set the log level to "info")

In short, log messages should not be formatted (by explicit use of the % operator, the format method, or f"" notation), but instead rely on the call to format the the logging method will perform.

Upvotes: 3

Related Questions