0

This is a follow-up question to the answer How to get non-blocking/real-time behavior from Python logging module? (output to PyQt QTextBrowser) provided by X.Jacobs.

In the Python logging module, the normal method of adding a custom handler is to define a handler class that inherits from logging.Handler (we'll call this CustomLogHandler). To attach it to logging process, we typically do this:

import logging

class CustomLogHandler(logging.Handler):
    ... (some code here)...

logger = logging.getLogger()
logger.addHandler(CustomLogHandler)

where addHandler is a method of the logger instance.

Question: Suppose we didn't want to get a logger (i.e. we don't want to do the above). Is is possible to attach the CustomLogHandler to logging itself?

See comments in How to get non-blocking/real-time behavior from Python logging module? (output to PyQt QTextBrowser) for context.

The premise is that it is possible to use custom handlers without any reference to the logger instance.

Community
  • 1
  • 1
Gilead
  • 1,263
  • 10
  • 21

1 Answers1

5

logging.getLogger() returns the root logger instance, there is no further 'up' from that object, and there is nothing else to attach a handler to beyond the root.

The module-level functions like logging.error() use the root logger; quoting from the documentation:

logging.error(msg[, *args[, **kwargs]])
Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug().

In other words, functions like logging.error() simply call getLogger().error().

Attaching your CustomLogHandler to the root logger is the correct way to add it to the module.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    I just read in the docs that it is possible to do this: `logging.getlogger('').addHandler(CustomLogHandler)`. That's the answer I needed. Thanks! – Gilead Jan 16 '13 at 21:20
  • 1
    @Gilead: You don't have to use a name; it is optional; the empty string is the same as not passing in a name at all. – Martijn Pieters Jan 16 '13 at 21:22
  • Thanks. I figured as much -- I just copied and pasted that from the docs. – Gilead Jan 16 '13 at 21:23