Python Logging: 输出格式与预期不符

huangapple go评论66阅读模式
英文:

Python Logging: Output not formatted as expected

问题

我遇到了Python日志输出的一些问题。

这是我如何初始化它的方式:

import logging

def get_logger():

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(levelname)s - %(message)s")

    handler.setFormatter(formatter)

    if not logger.hasHandlers():
        logger.addHandler(handler)

    return logger

我有一个函数,当它被调用时应该提供一个日志条目:

def app():
    logger = get_logger()
    logger.debug("Page 1 Initiated")

在我的主文件中,我有这个:

if __name__ == '__main__':
    logger = get_logger()
    logger.debug("Started")
    run_ui()

run_ui() 将调用 app()

这是我的问题:当我运行 main.py 时,我会在控制台中得到以下日志输出:

2023-04-03 15:15:24.354 DEBUG   src.logging_config: Started
2023-04-03 15:15:26.509 Page 1 Initiated

似乎我的格式化器没有正常工作?我已经设置了它,以便我可以得到级别名称,后面跟着消息。但每次我都只得到第二行输出。根据我的格式化器,我期望得到这个:

DEBUG Page 1 Initiated

我是不是漏掉了什么?

英文:

I am having some issues with the output of my Python logs.

Here is how I am initiating it:

import logging

def get_logger():

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(levelname)s - %(message)s")

    handler.setFormatter(formatter)

    if not logger.hasHandlers():
        logger.addHandler(handler)

    return logger

I have a function here which should provide a log entry when it is called

def app():
    logger = get_logger()
    logger.debug("Page 1 Initiated")

In my main file I have this:

if __name__ == '__main__':
    logger = get_logger()
    logger.debug("Started")
    run_ui()

run_ui() will call app()

Here is my issue: When I run main.py I will get the following log output in my console

2023-04-03 15:15:24.354 DEBUG   src.logging_config: Started
2023-04-03 15:15:26.509 Page 1 Initiated

It seems like my formatter is not working properly? I have it set so that I get level name, followed by the message. But I just keep getting that second line of output every time. Based on my formatter, I am expecting to get this:

DEBUG Page 1 Initiated

Am I missing something here?

答案1

得分: 1

你正在将处理程序附加到记录器层次结构的子记录器:

logger = logging.getLogger(__name__)

当你想要打印记录器的名称(即查看记录器被调用的包,根据包过滤日志等)时,子记录器非常有用。然而,如果你想要格式化消息,通常会将处理程序附加到root记录器,就像这样:

if not logging.getLogger().hasHandlers():
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logging.getLogger().addHandler(handler)

在记录日志时,最好仍然使用子记录器,这些日志会自动传播到根记录器。

参见:Python记录器层次结构

英文:

You are attaching your handlers to child loggers of the logger hierarchy:

logger = logging.getLogger(__name__)

Child loggers are useful when you want to print the name of the logger (i.e. see the package where the logger was called, filter logs based on packages etc.). However, if you want to format messages, usually the handlers are attached to the root logger, like this:

if not logging.getLogger().hasHandlers():
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logging.getLogger().addHandler(handler)

It is still best to use the child logger when logging, those logs are propagated to the root logger automatically.

See: Python logging hierarchy

huangapple
  • 本文由 发表于 2023年4月4日 03:25:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定