【问题标题】:logging for multi-module program多模块程序的日志记录
【发布时间】:2022-01-17 15:21:39
【问题描述】:

我想在我的程序中添加一个日志记录机制。我的项目目录的基本结构是这样的:

.
├── README.md
└── src
    ├── cli.py
    ├── module1.py
    ├── module2.py
    └── module3.py

cli.py 导入所有其他 module[1-3].py但是,我也使用所有其他模块作为独立的可执行文件(即使在此项目的上下文之外)。即我使用所有这些命令:

$ python3 cli.py <args>
$ python3 module1.py
$ python3 module2.py <args>

文件的基本结构:

# cli.py
import logging
from rich.logging import RichHandler
import module1

formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s')
file_handler = logging.FileHandler('cli.log')
file_handler.setFormatter(formatter)
console_handler = RichHandler()
log = logging.getLogger() # root handler
log.addHandler(file_handler)
log.addHandler(console_handler)

if __name__ == '__main__':
    log.error('Hi from cli.py')
    module1.foo()
# module1.py
import logging

log = logging.getLogger(__name__)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s')
file_handler = logging.FileHandler('module1.log')
file_handler.setFormatter(formatter)
log.addHandler(file_handler)


def foo():
    log.error('Hi from module1.py')

if __name__ == '__main__':
    foo()

运行结果:

$ python3 cli.py
[12/14/21 11:29:05] ERROR    Hi from cli.py
                    ERROR    Hi from module1.py
$ python3 module1.py
Hi from module1.py

我想知道如何配置日志记录,所以即使我将执行$ python3 module1.py,我仍将拥有与根 (RichHandler) 中定义的格式相同的格式。 当我试图在 module1.py 中设置一个额外的格式时,它导致了一个重复的处理程序。
所以基本上我想实现这种行为:

$ python3 cli.py
[12/14/21 11:29:05] ERROR    Hi from cli.py      # also logged to cli.log
                    ERROR    Hi from module1.py  # also logged to cli.log and module1.log 
$ python3 module1.py
[12/14/21 11:29:05] ERROR    Hi from module1.py  # also logged to module1.log

【问题讨论】:

  • 如果我理解正确,您希望它的模块有自己的记录器吗?

标签: python logging module rich


【解决方案1】:

我相信我最近遇到了同样的问题。在您的导入文件中,不要定义“日志”。

而只是导入日志,并使用,例如:

logging.error('Hi from module1.py')

然后这将从 cli.py 中的日志对象按预期输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    相关资源
    最近更新 更多