1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] python logger init to `level=20` (INFO) do not show debug if I later change to...

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I changed my logging default level to logging.INFO (20) from Logging.DEBUG (10), but then it wont show debug messages if I change logLevel to 'DEBUG' later on in the code:

    Old config works fine:

    >>> import mylog
    >>> log1 = mylog.mylogger('log1',level=10) # default is DEBUG
    added logger log1 of level:10
    >>> log1
    <Logger log1 (DEBUG)>
    >>> log1.debug("works")
    20241007163742.800|DEBUG|<stdin>:1|works
    >>> log1.setLevel(20)
    >>> log1
    <Logger log1 (INFO)>
    >>> log1.info("works")
    20241007163825.042|INFO|<stdin>:1|works
    >>> log1.debug("should not show")
    >>>


    I can also go back to debug and it works:

    >>> log1.setLevel(10)
    >>> log1
    <Logger log1 (DEBUG)>
    >>> log1.debug("works")
    20241007164010.113|DEBUG|<stdin>:1|works


    All fine, except default logging is DEBUG which logs a bit too much if I do not change the loglevel.

    But if I defaults to level=20 I can't see DEBUG after a log2.setLevel(10):

    >>> log2 = mylog.mylogger('log2',level=20) # default is INFO
    added logger log2 of level:20
    >>> log2
    <Logger log2 (INFO)>
    >>> log2.info("works")
    20241007164505.921|INFO|<stdin>:1|works
    >>> log2.debug("should not show")
    >>> log2.setLevel(10)
    >>> log2
    <Logger log2 (DEBUG)>
    >>> log2.info("works as before")
    20241007164628.199|INFO|<stdin>:1|works as before
    >>> log2.debug("why is this not showing")
    >>>


    my simplified log module mylog.py:

    import logging
    def mylogger(name:str, level:int=logging.INFO) -> logging.Logger:
    """ default logger """
    logger = logging.getLogger(name)
    if logger.hasHandlers():
    print(f"logger {name} already has handler")
    else:
    logger.setLevel(level)
    console_fmt = "%(asctime)s.%(msecs)03d|%(levelname)s|%(pathname)s:%(lineno)d|%(message)s"
    datefmt = "%Y%m%d%H%M%S"
    ch = logging.StreamHandler()
    ch.setLevel(level)
    ch.setFormatter(logging.Formatter(file_fmt, datefmt))
    logger.addHandler(ch)
    logger.propagate = False
    print(f"added logger {name} of level:{logger.level}")
    return logger


    Could it be the level of the StreamHandler()?

    How can I check this after it has been set up?

    >>> loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
    >>> loggers
    [<Logger log1 (DEBUG)>, <Logger log2 (DEBUG)>]

    Continue reading...

Compartilhe esta Página