[Python] root logger not respecting log level Python

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to get my head around Python logging in general and I have created a small code to do so. Below is my main code file:

    import logging.config

    logging.config.fileConfig('logging-2.conf')
    logger = logging.getLogger('main')
    import auxillary


    logger.info("Info message from main file")
    logger.warning("This is a warning message from main file")


    My logging configuration file goes as follows:

    [loggers]
    keys=root, main

    [handlers]
    keys=mainhandler, roothandler

    [formatters]
    keys=mainformatter

    [logger_root]
    level=ERROR
    handlers = roothandler

    [logger_main]
    level=DEBUG
    handlers=mainhandler
    qualname=main
    propagate=1

    [handler_roothandler]
    class=StreamHandler
    args=(sys.stdout,)

    [handler_mainhandler]
    class=FileHandler
    formatter=mainformatter
    args=("main.log",)

    [formatter_mainformatter]
    format=%(asctime)s - %(name)s - %(levelname)s - %(message)s


    And below is the code of the auxillary.py file:

    import logging

    module_logger = logging.getLogger('main.auxiliary')

    module_logger.info("Info statement from auxillary function")
    module_logger.warning("warning message from auxillary function")


    When I run the code I get the following output:

    Info statement from auxillary function
    warning message from auxillary function
    Info message from main file
    This is a warning message from main file


    And the contents of my main.log file is as follows:

    2019-07-28 16:52:05,710 - main.auxiliary - INFO - Info statement from auxillary function
    2019-07-28 16:52:05,710 - main.auxiliary - WARNING - warning message from auxillary function
    2019-07-28 16:52:05,710 - main - INFO - Info message from main file
    2019-07-28 16:52:05,710 - main - WARNING - This is a warning message from main file


    In other words, even after setting the log level to ERROR for the root logger it is printing all the messages.

    Any idea why is this happening? How should I force the root logger to only print messages from error and above even if propagate is true for it.

    Continue reading...

Compartilhe esta Página