如何设置记录器对象的记录级别?

时间:2019-03-28 08:52:22

标签: python logging

当我尝试使用日志记录库进行记录时,我无法在代码中找到错误。即使我将最低日志级别设置为DEBUG,记录器也会创建一个从WARNING开始的日志文件。

import logging

my_logger = logging.getLogger("our logger")  

# Remove all handlers associated with my_logger object. 
# This is only done so that we can run this block mult. times.
for handler in my_logger.handlers[:]:
    my_logger.removeHandler(handler)

# let's create a handler and set the logging level
my_handler_for_file = logging.FileHandler("custom logging.log", mode='w')
my_handler_for_file.setLevel(logging.DEBUG)   
# try to set it to logging.CRITICAL and it will only log CRITICAL, 
# so it does work but neither for DEBUG nor INFO!

# add the handlers to our custom logger
my_logger.addHandler(my_handler_for_file)

# let's create some logs
my_logger.debug('This is a debug message')
my_logger.info('This is an info message')
my_logger.warning('This is a warning message')
my_logger.error('This is an error message')
my_logger.critical('This is a critical message')

这是日志文件中的输出:

This is a warning message  
This is an error message  
This is a critical message

这就是我所期望的:

This is a debug message  
This is an info message  
This is a warning message  
This is an error message  
This is a critical message

有人知道这里出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

您还需要在记录器上设置级别。

my_logger.setLevel(logging.DEBUG)

这是因为记录器和处理程序都根据其级别过滤消息。