简体   繁体   中英

Logging to console for child loggers is enabled only after logging from root logger in python

Take a look at this code:

import logging

logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger('TEST').setLevel(logging.DEBUG)

#logging.debug('message')

logging.getLogger().debug('message')
logging.getLogger('TEST').debug('message')

With the commented line logging.debug('message') when I run the script I don't see ANY log message in the console as I expect. I expect to see two log messages from root and TEST loggers, but I see nothing.

But when I uncomment the line, I see three log messages as expected.

What is the problem?

PS: My python version: 3.10.5

You didn't configure any handlers, and handlers are the things that output logging messages. The line

logging.debug('message')

does an implicit configuration of a handler (as documented here , in the last paragraph) and so you get messages output. That last paragraph says:

This function [meaning logging.debug() ] (as well as info() , warning() , error() and critical() ) will call basicConfig() if the root logger doesn't have any handler attached.

See also the advanced tutorial , which talks about what roles loggers, handlers, filters and formatters play.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM