我正在尝试为我的日志文件和流设置不同的记录器级别,并且我(似乎)跟随演示(https://docs.python.org/3/howto/logging-cookbook.html)到点。但是,在我的实际代码中它不起作用。在测试脚本中运行这个演示是有效的:
import logging
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
print(logger.handlers)
print(logger)
结果是
alex@alexpc:~/Projects/claritydb$ python test.py ; cat spam.log
2019-09-16 11:53:44,293 - simple_example - ERROR - error message
2019-09-16 11:53:44,293 - simple_example - CRITICAL - critical message
[<StreamHandler <stderr> (ERROR)>, <FileHandler /home/Projects/claritydb/spam.log (DEBUG)>]
<Logger simple_example (DEBUG)>
2019-09-16 11:53:44,293 - simple_example - DEBUG - debug message
2019-09-16 11:53:44,293 - simple_example - INFO - info message
2019-09-16 11:53:44,293 - simple_example - WARNING - warn message
2019-09-16 11:53:44,293 - simple_example - ERROR - error message
2019-09-16 11:53:44,293 - simple_example - CRITICAL - critical message
但是由于某种原因,这将无法在实际代码中正确执行:
class MyClass(object):
def __init__(self,
verbosity_stream="WARNING",
verbosity_log="INFO"):
self.logger = self.setup_logger(verbosity_stream=verbosity_stream, verbosity_log=verbosity_log)
def setup_logger(self, verbosity_stream="ERROR", verbosity_log="WARNING"):
# Create a custom logger
logger = logging.getLogger(f"do_stuff")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(f"do_stuff.log", mode='w')
fh.setLevel(getattr(logging, verbosity_log))
ch = logging.StreamHandler()
ch.setLevel(getattr(logging, verbosity_stream))
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to the self.logger
logger.addHandler(ch)
logger.addHandler(fh)
print(logger.handlers)
return logger
对 self.logger 的任何调用都会在 logging.DEBUG 级别输出到控制台和日志文件——这显然不是我想要的。我很困惑我错过了什么,因为当我问主要方法它的文件处理程序是什么时
print(self.logger.handlers)
print(self.logger)
[<StreamHandler <stderr> (ERROR)>, <FileHandler /home/Projects/claritydb/do_stuff.log (DEBUG)>]
<Logger do_stuff (DEBUG)>
这与测试用例相同,但我的控制台和日志文件中都有所有信息级别的输出。更改我的 handler.setLevel 命令对输出没有影响,唯一改变它的是将 setLevel 命令更改为定义最顶部的初始记录器调用(即 ch.setLevel 和 fh.setLevel 无效,但 logger.setLevel 确实[而且我认为它应该只是初始过滤器)。
这让我发疯,有人知道吗?
EDIT1:更改
logger = logging.getLogger(f"do_stuff")
线到
logger = logging.getLogger()
似乎解决了这个问题,但我不知道为什么......