1

I know this question has been asked like a million times before, but I just don't know why this:

import logging
from mylib import MyClass

hdlr = logging.FileHandler("MyLog.log", encoding="utf-16", mode="w")
hdlr.setFormatter(
    logging.Formatter("[%(levelname)s] %(name)s <%(module)s.%(funcName)s>  %(message)s")
)
hdlr.setLevel(logging.DEBUG)

myobj = MyClass(handlers=[hdlr])

where myclass.py which defines MyClass looks like this:

import logging
logger = logging.getLogger("MyClass")

class MyClass:
    def __init__(self, handlers):
        for hdlr in handlers:
            logging.root.addHandler(hdlr)

This only outputs WARNING messages in the file.

I read this question and I verified that I am not doing any logging before adding the handlers to root logger.

However replacing this line,

hdlr.setLevel(logging.DEBUG)

to this:

logging.root.setLevel(logging.DEBUG)

works, when it apparently (jump to the EDIT) shouldn't?

Some background info: MyClass is a library I am working on. Its root __init__.py contains no logging code, (although I think libraries should have some logging related code in that file).

demberto
  • 489
  • 5
  • 15

1 Answers1

1

It doesn't matter what the level of the handler is, if the message never makes it to the handler. By default, the root logger level is WARN; it won't dispatch INFO or DEBUG messages to any handlers. When you set the root logger to DEBUG, it will send DEBUG messages to handler(s), which then can decide what to do with them based on their level settings.

Related to logging | error() gets sent to FileHandler... but not other Logging Levels

kielni
  • 4,779
  • 24
  • 21
  • Ahh, I didn't know this. So I should add `logging.root.setLevel(hdlr.getLevel())` in `MyClass.__init__()`? What if there are multiple handlers? Should I just set it to `DEBUG` always? – demberto Oct 30 '21 at 18:55
  • A library can contain log statements, but should not configure logging. See https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library "It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library." – kielni Oct 30 '21 at 21:01