繁体   English   中英

Python-从多个模块登录到旋转文件,而无需打印到控制台

[英]Python - Logging from multiple modules to rotating files without printing to console

我正在尝试将日志记录添加到中等规模的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.

这是我尝试在模块中执行的操作的示例:

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.')

现在,这是我的问题。 目前,我无提示地将消息记录到旋转文件中。 但是我只会收到警告,错误和严重消息。 尽管设置了handler.setLevel(logging.DEBUG)

如果我取消注释logging.basicConfig(level=logging.DEBUG) ,那么我会在日志文件中获取所有消息,但也会获得打印到终端的消息。

如何将所有超过指定阈值的消息发送到日志文件,而不将其输出到终端?

谢谢!

更新:根据此答案 ,看来调用logging.basicConfig(level=logging.DEBUG)自动将StreamHandler添加到Root记录器,您可以将其删除。 当我确实删除它时,只剩下RotatingFileHandler ,消息不再打印到终端。 我仍然想知道为什么在设置handler.setLevel(logging.DEBUG)时必须使用logging.basicConfig(level=logging.DEBUG)设置消息级别阈值。 如果有人能对这些问题有更多的了解,那么我们将不胜感激。

您还需要在记录器本身上调用设置记录级别。 我相信,在默认情况下,在记录日志记录级别为logging.WARNING

例如

root_logger = logging.getLogger('')
root_logger.setLevel(logging.DEBUG)

# Add the handler to the root logger
root_logger.addHandler(handler)

记录器日志级别确定记录器实际记录的内容(即,实际上将哪些消息传递给处理程序)。 处理程序日志级别确定它将实际处理的内容(即,实际上将哪些消息输出到文件,流等)。 因此,您可能会在记录器上附加多个处理程序,每个处理程序都处理不同的日志级别。

这是一个SO答案 ,解释了它的工作方式

暂无
暂无

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

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