子模块中的日志记录级别字符串不正确

时间:2018-08-15 20:40:04

标签: python logging

我正在使用标准库日志记录模块,但碰到了我无法解释的内容:即,当我从子模块获取记录器时,看来与记录器级别相关联的字符串为WARNING ,无论它实际设置为什么日志级别。更令人困惑的是,子模块记录器以正确的级别记录消息。如果在下面运行main.py(首先更改日志文件名),您将明白我的意思。控制台打印出other_module的记录器级别为WARNING,但它忠实地记录了较低级别的消息。

如果可以的话,我实际上有点需要与级别关联的字符串。这种行为是错误,还是我误会了什么?

main.py

import logging
import other_module

def create_logger(log_level):
    level = log_level.upper()
    switcher = {"DEBUG": logging.DEBUG,
                "INFO": logging.INFO,
                "WARNING": logging.WARNING,
                "ERROR": logging.ERROR,
                "CRITICAL": logging.CRITICAL}
    logging.basicConfig(filename='C:/logs/log.log', #Change this
                        format="%(asctime)s | %(name)s [Line %(lineno)d] | %(levelname)s: %(message)s",
                        datefmt="%m/%d/%Y %H:%M:%S",
                        level=switcher[level])
    logger = logging.getLogger("root")
    return logger

def main():
    log = create_logger('DEBUG')
    log.debug("Message from main")
    other_module.test_function()

if __name__ == '__main__':
    main()

other_module.py

import logging
log = logging.getLogger(__name__)
print("other_module log level is {}".format(logging.getLevelName(log.getEffectiveLevel())))

def test_function():
    log.debug('Message from other_module')

1 个答案:

答案 0 :(得分:0)

其原因是other_module.py是在配置日志记录系统之前加载的,并使用默认值实例化了它的记录器。

如果将basicConfig调用放在import other_module之前,则日志记录级别将达到预期水平。

相关问题