[Python] Why are log messages from imported module not shown?

Discussão em 'Python' iniciado por Stack, Maio 7, 2025.

  1. Stack

    Stack Membro Participativo

    I can't seem to raise the log level of a module's logger. I have a script which uses the root logger, and I want to only print its ERROR logs. However, the module I import, I would like to log granually on DEBUG.

    In mymodule.py:

    import logging
    log = logging.getLogger(__name__)
    log.setLevel(logging.ERROR)

    def do_something():
    log.DEBUG("Module debug")
    log.INFO("Module info")
    log.WARNING("Module warning")
    log.ERROR("Module error")


    and in myscript.py:

    import mymodule
    import logging

    logging.getLogger().setLevel(logging.ERROR)

    modulelogger = logging.getLogger("mymodule")
    print(modulelogger)

    modulelogger.setLevel(logging.DEBUG)
    print(modulelogger)

    mymodule.do_something()

    log.DEBUG("Script debug")
    log.INFO("Script info")
    log.WARNING("Script warning")
    log.ERROR("Script error")


    Output when running myscript.py:

    Module error
    <Logger mymodule (ERROR)>
    <Logger mymodule (DEBUG)>
    Error:root: script error

    1. Why am I seeing the level of the "mymodule" as WARNING initially? The module defines it as ERROR?
    2. Why am I not seeing the INFO and DEBUG logs by the "mymodule" logger after setting its level to DEBUG?

    Continue reading...

Compartilhe esta Página