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.

3
  • What do you expect to happen when you 'attach the CustomLogHandler to logging itself'? Commented Jan 16, 2013 at 21:10
  • I'm looking to use logging.error() instead of logger.error(). Commented Jan 16, 2013 at 21:11
  • I'm not sure why this got downvoted (by whomever it is) -- the question is a reasonable one. The answer given is also the correct one. Commented Jan 16, 2013 at 21:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: 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.
Thanks. I figured as much -- I just copied and pasted that from the docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.