简体   繁体   English

日志记录 - 将级别从 INFO 更改为 DEBUG 会禁用所有日志记录消息

[英]Logging - changing level from INFO to DEBUG disables all logging messages

I have only recently started using Python logging module.我最近才开始使用 Python 日志记录模块。 I've read docs and some guides, but still am confused as to why logging levels work the way they do.我已经阅读了文档和一些指南,但仍然对为什么日志级别的工作方式感到困惑。

I have a logger defined in the beginning of the script:我在脚本的开头定义了一个记录器:

import logging

log_file = f'test.log'
logger = logging.getLogger(__name__)
f_handler = logging.FileHandler(log_file)
f_handler.setLevel(logging.INFO)
f_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s',
                             datefmt='%d/%m/%Y %H:%M:%S')
f_handler.setFormatter(f_format)
logger.addHandler(f_handler)
logger.info('Initialising.')

Then throughout the code I have multiple calls to this logger - some info , some exceptions and warnings as well.然后在整个代码中,我多次调用这个记录器 - 一些info ,一些exceptionswarnings

Yet, for some reason with the current setup I only get one warning message, if any, although I though that I should be getting all messages above and including INFO level.然而,由于当前设置的某种原因,我只收到一条warning消息(如果有),尽管我认为我应该收到高于并包括INFO级别的所有消息。

To try and test it I switched the logger to DEBUG but I got an empty log as a result.为了尝试和测试它,我将记录器切换到DEBUG但结果我得到了一个空日志。

At the very least I expect to see the following info messages in the log:至少我希望在日志中看到以下info消息:

self.logger.info('Initialising.') #Right in the __init__ of the class
self.logger.info(f'Using {self.export_file} for export data.') #This one should always be printing unless script fails at the very start
self.logger.info(f'Using {self.model_file} model to predict values.') #Same with this one
self.logger.info('Encoding into a model completed successfully.') #This one as well if script completes successfully, which it normally does

I must be doing something wrong, but I'm not sure what exactly.我一定是做错了什么,但我不确定到底是什么。

from setLevel :setLevel

When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger).创建记录器时,级别设置为 NOTSET(当记录器是根记录器时,这会导致处理所有消息,或者当记录器是非根记录器时将其委托给父级)。 Note that the root logger is created with level WARNING .请注意,根记录器是使用级别 WARNING 创建的

Also take a look at logging flow scheme here .还可以在此处查看日志记录流程方案。

You should call self.logger.setLevel(logging.INFO) to adjust root logger level.您应该调用self.logger.setLevel(logging.INFO)来调整根记录器级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM