Python日志记录 - 在多个模块中配置文件与根日志记录器

4

当我在配置文件中配置根记录器时,其他子记录器不会遵循相同的配置。

main.py

import logging
import logging.config
import test


logging.config.fileConfig("logger.ini")
logger = logging.root
logger.critical("main")
test.f()

test.py

import logging

logger = logging.getLogger(__name__)

def f():
    print "inside f"
    logger.critical("Test")
    print logger.parent.name
    print logger.parent.handlers

logger.ini

[loggers]
keys=root

[handlers]
keys=console
[formatters]
keys=form
[logger_root]
level=DEBUG
handlers=console

[handler_console]
class=StreamHandler
formatter=form
args=()

[formatter_form]
format=%(levelname)s:%(name)s:%(message)s

当我运行程序时,我得到的结果不是我想要的。
CRITICAL:root:main
inside f
root
[<logging.StreamHandler object at 0x00000000021C4908>]

但是我没有来自另一个文件的日志。我认为如果子进程没有任何处理程序,他会将日志发送到他的父进程。不知道为什么我看不到日志?或者如何解决它?

1个回答

7
这里的情况是,在您调用main.py中的logging.config.fileConfig("logger.ini")之前,在test.py中提取的日志记录器已被创建。一旦调用fileConfig,任何未在配置文件中指定的预先存在的日志记录器都将被删除。
我可以建议两种解决方法:
1. 不要在模块的全局范围内调用logging.getLogger,而是仅在需要在函数/方法内部使用记录器时才进行调用。 2. 更改代码,当调用fileConfig()时,指定:logging.config.fileConfig("logger.ini", disable_existing_loggers=False)。这会导致在应用配置之前创建的任何记录器都得以保留并且不会被禁用。
有关选项#2的详细信息,请参见https://docs.python.org/2/library/logging.config.html#logging.config.fileConfig

谢谢,它运行得很好。我更喜欢第二个选项。 :D - Nazime Lakehal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接