我正在尝试将日志记录添加到一个中等规模的 Python 项目中,同时将中断降至最低。我想从多个模块记录到静默旋转文件(不将消息打印到终端)。我尝试修改这个示例,除了一个问题之外,我几乎拥有了我需要的功能。
以下是我尝试在主脚本中配置内容的方法:
import logging
import logging.handlers
import my_module
LOG_FILE = 'logs\\logging_example_new.out'
#logging.basicConfig(level=logging.DEBUG)
# Define a Handler which writes messages to rotating log files.
handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=100000, backupCount=1)
handler.setLevel(logging.DEBUG) # Set logging level.
# Create message formatter.
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# Tell the handler to use this format
handler.setFormatter(formatter)
# Add the handler to the root logger
logging.getLogger('').addHandler(handler)
# Now, we can log to the root logger, or any other logger. First the root...
logging.debug('Root debug message.')
logging.info('Root info message.')
logging.warning('Root warning message.')
logging.error('Root error message.')
logging.critical('Root critical message.')
# Use a Logger in another module.
my_module.do_something() # Call function which logs a message.
Run Code Online (Sandbox Code Playgroud)
这是我在模块中尝试执行的示例:
import logging
def do_something():
logger = logging.getLogger(__name__)
logger.debug('Module debug message.')
logger.info('Module info message.')
logger.warning('Module warning message.')
logger.error('Module error message.')
logger.critical('Module critical message.')
Run Code Online (Sandbox Code Playgroud)
现在,这是我的问题。目前,我将消息默默地记录到旋转文件中。但我只收到警告、错误和关键消息。尽管设定handler.setLevel(logging.DEBUG)。
如果我取消注释logging.basicConfig(level=logging.DEBUG),那么我会得到日志文件中的所有消息,但也会得到打印到终端的消息。
如何将高于指定阈值的所有消息获取到我的日志文件而不将其输出到终端?
谢谢!
更新:
根据此答案,看来调用会logging.basicConfig(level=logging.DEBUG)自动将 a 添加StreamHandler到根记录器,您可以将其删除。当我删除它时,只留下我的RotatingFileHandler,消息不再打印到终端。我仍然想知道为什么logging.basicConfig(level=logging.DEBUG)当我设置handler.setLevel(logging.DEBUG). 如果有人能对这些问题有更多的了解,我们将不胜感激。
您还需要在记录器本身上调用设置日志记录级别。我相信默认情况下,记录器的日志记录级别是logging.WARNING
前任。
root_logger = logging.getLogger('')
root_logger.setLevel(logging.DEBUG)
# Add the handler to the root logger
root_logger.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)
记录器日志级别决定记录器实际记录的内容(即,哪些消息将实际传递给处理程序)。处理程序日志级别决定了它实际处理的内容(即实际输出到文件、流等的消息)。因此,您可能会将多个处理程序附加到一个记录器,每个处理程序处理不同的日志级别。
这是一个SO 答案,解释了它的工作方式