我正在尝试使用 logging.basicConfig 来记录所有内容,并使用 logging.hanlers.RotatingFileHandler 来获取 maxBytes=1000000 和 backupCount=5。 问题是,当我使用 RotatingFileHandler 时,它也会记录一些重复的输出。 我尝试删除 basicConfig 并仅使用 RotatingFileHandler 但它没有记录我想要的每条消息。
例子:
logging.basicConfig(format=f, datefmt=date, level=lvl, filename=file_name)
handler = logging.handlers.RotatingFileHandler(file_name, maxBytes=1000000, backupCount=5)
logging.getLogger('').addHandler(handler)
我通过以下方式更改了它以删除 basicConfig:
handler = logging.handlers.RotatingFileHandler(file_name, maxBytes=1000000, backupCount=5)
handler.setFormatter(f)
handler.setLevel(lvl)
logging.getLogger('').addHandler(handler)
上面没有工作,因为 RotatingFileHandler 没有记录我想要的每条消息。为什么?
请您参考如下方法:
根记录器的默认级别是logging.WARNING。这会导致不太严重的消息被忽略(参见 Logging Levels )。为了让根记录器委托(delegate)所有消息,需要将其级别设置为 logging.NOTSET。
import logging
import logging.handlers
# Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
logging.getLogger('').setLevel(logging.NOTSET)
# Add file rotatin handler, with level DEBUG
rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
rotatingHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rotatingHandler.setFormatter(formatter)
logging.getLogger('').addHandler(rotatingHandler)
log = logging.getLogger("myApp." + __name__)
log.debug('Hello, debug message.')
log.info('Hello, info message.')
log.warning('Hello, warning message.')
log.error('Hello, error message.')
