0

I'm using the python logging library with python 3.9.

I want to avoid the expense of doing a decode operation as most times I won't have debug level logging enabled.

stdout, _ = process.communicate()
logging.debug("stdout: %s", stdout.decode('utf-8'))

One solution to avoid the decode call when logging is disabled is to explicitly check isEnabledFor, however, this adds a lot of noise to the code that I would like to avoid.

if logging.getLogger().isEnabledFor(logging.DEBUG):
    logging.debug("stdout: %s", stdout.decode('utf-8'))

I'm hoping there's a string formatting option that will defer the decode operation and be easy to read.

logging.debug("stdout: %(bs.utf-8)", stdout)

Does such an operation or formatter exist?

Matthew
  • 24,703
  • 9
  • 76
  • 110
  • "decode"? In any case Python use ofn "encoding" internally (it is transparent, so we consider `decode`: we see only the Unicode semantic). In any case, if the string has only ASCII.Latin1 characters, there is no real "decode" or "encode". And if the string is not latin1, the internal encoding is either UTF16 or UTF-32. So most of the work is done anyway (and I do not think it is the slowest part of "logging") – Giacomo Catenazzi Aug 22 '23 at 14:00
  • See https://stackoverflow.com/questions/21377020/python-how-to-do-lazy-debug-logging – k314159 Aug 22 '23 at 15:07

0 Answers0