Root inherited python logger level set before warning by default

In my program, I first define a logger that looks something like this:

def start_logger():
        fh = logging.handlers.RotatingFileHandler('logger.log', 
                                                  maxBytes=1000000, 
                                                  backupCount=100)
        fh.setLevel(logging.DEBUG)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)

        fh_fmt = '%(asctime)s %(levelname)8s %(message)s [%(filename)s:%(lineno)d]'
        #fh_fmt = '%(asctime)s - %(funcName)s - %(levelname)s - %(message)s'

        ch_fmt = '%(asctime)s %(levelname)8s %(message)s [%(filename)s:%(lineno)d]'
        #ch_fmt = '%(funcName)s - %(levelname)s - %(message)s'

        fh.setFormatter(logging.Formatter(fh_fmt))
        ch.setFormatter(logging.Formatter(ch_fmt))

        root = logging.getLogger()
        root.addHandler(fh)
        root.addHandler(ch)

Then I have some files that are called from my main program. For them to work correctly, I need to do the following:

import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.debug("This debug message is ounly output when I set the level again to debug for this file. Otherwise the the log level for this file is WARNING.")

Why is the default level for all modules that I import set to alert. Why do I need to set the level in DEBUG again for each of them when they import my root log using log = logging.getLogger ( name )? Is this the best way to create a registration module through a package with various modules, or is there a better solution?

+4
1

, Handler.setLevel :

lvl. , , lvl, . , NOTSET ( ).

, , lvl, . , DEBUG ( ), , . , , .

setLevel - , . Logger.setLevel:

lvl. , , lvl, . NOTSET ( , , root). , .

" , NOTSET, - , , NOTSET, .

, NOTSET, , , , .

, . NOTSET, , WARNING. , .

TL; : : , . , :

def start_logger():
    fh = logging.handlers.RotatingFileHandler('logger.log', 
                                              maxBytes=1000000, 
                                              backupCount=100)

    ch = logging.StreamHandler(sys.stdout)

    fh_fmt = '%(asctime)s %(levelname)8s %(message)s [%(filename)s:%(lineno)d]'
    #fh_fmt = '%(asctime)s - %(funcName)s - %(levelname)s - %(message)s'

    ch_fmt = '%(asctime)s %(levelname)8s %(message)s [%(filename)s:%(lineno)d]'
    #ch_fmt = '%(funcName)s - %(levelname)s - %(message)s'

    fh.setFormatter(logging.Formatter(fh_fmt))
    ch.setFormatter(logging.Formatter(ch_fmt))

    logging.basicConfig(level=logging.DEBUG)
    root = logging.getLogger()
    root.addHandler(fh)
    root.addHandler(ch)

, setLevel.

, : . ( , , , , , .)

EDIT: , setLevel, , . , , basicConfig. logging.basicConfig , ( , ). , , , .

+3

Source: https://habr.com/ru/post/1680218/


All Articles