Reputation: 1263
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.
Upvotes: 0
Views: 2343
Reputation: 1121584
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.
Upvotes: 5