variable
variable

Reputation: 9724

Does creating new logger for module still use the root logger name?

I am looking at this article: https://docs.python.org/3.7/howto/logging.html#logging-basic-tutorial

The paragraph:

The root of the hierarchy of loggers is called the root logger. That’s the logger used by the functions debug(), info(), warning(), error() and critical(), which just call the same-named method of the root logger. The functions and the methods have the same signatures. The root logger’s name is printed as ‘root’ in the logged output.

I am confused because once you create a logger using logger = logging.getLogger(__name__) and use logger.info/debug/etc., the name of the module should be printed and not root. Why does the paragraph say: "...which just call the same-named method of the root logger"

Upvotes: 2

Views: 485

Answers (1)

shmee
shmee

Reputation: 5101

The wording is important.

[...] That’s the logger used by the functions debug(), info(), warning(), error() and critical(), which just call the same-named method of the root logger. [...]

The paragraph refers to the module-level utility functions debug(), info(), warning(), error() and critical(). All of them, in fact, operate on the root logger, e.g.:

def debug(msg, *args, **kwargs):
    """
    Log a message with severity 'DEBUG' on the root logger. If the logger has
    no handlers, call basicConfig() to add a console handler with a pre-defined
    format.
    """
    if len(root.handlers) == 0:
        basicConfig()
    root.debug(msg, *args, **kwargs)

These module-level functions can be found in the documentation.

Of course, when creating your own logger via logging.getLogger(__name__) and calling the respective methods on that instance, you operate on your logger, not the root (primarily, there's still propagation, unless explicitly disabled).

Edit:
I just realized that this question, and your previous one, have already been answered by George's excellent, in-depth reply to your slightly earlier question. I highly recommend to read it thoroughly.

Upvotes: 3

Related Questions