Python日志记录:如何从所有日志记录程序中删除处理程序?

2024-03-29 11:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个具有特定日志处理程序的上下文管理器,用户可以将其添加到自己选择的日志记录器中

以下是上下文代码:
# module mycontext.py
import logging

class myContext(object):
    def __init__(self):
        pass
    def __enter__(self):
        # Create a specific loghandler:
        logformat = logging.Formatter()
        self.loghandler = logging.FileHandler('mycontext.log')
        self.loghandler.setFormatter(logformat)
        return self
    def __exit__(self, etype, evalue, tb):
        self.loghandler.close()
        # Now remove that handler everywhere
        # ...?
下面是一个示例用法:
# Main application
from mycontext import myContext
import logging
logger = logging.getLogger(__name__)

with myContext() as ctxt:
    # mycontext gives the possibility to log messages to it: 
    logger.addHandler(ctxt.loghandler)
    
    pass

既然上下文已退出,我如何确保ctxt.loghandler已从所有记录器中删除

当前繁琐的解决方案

  1. 首先,我当然可以将with中的所有代码包装在try...finally中,但如果不利用我的上下文管理器,那就很烦人了
  2. 当然,仅仅__exit__中的del self.loghandler并不会从所有处理程序列表中删除实际对象
  3. "logging won't shutdown"所示,logging.shutdown(self.loghandler)不起作用
  4. 我的当前工作解决方案是迭代所有记录器:
    def __exit__(self, etype, evalue, tb):
        self.loghandler.close()
        logging.root.removeHandler(self.loghandler)
        for logname, logger in logging.root.manager.loggerDict.items():
            logger.removeHandler(self.loghandler)

难道没有更有效的解决方案吗?像是引用相关记录器的处理程序属性


Tags: 代码importself处理程序管理器loggingdefexit
1条回答
网友
1楼 · 发布于 2024-03-29 11:28:43

您可以尝试以这种方式删除所有处理程序-ref

    def __exit__(self, etype, evalue, tb):
        logger = logging.getLogger()
        while logger.hasHandlers():
            logger.removeHandler(logger.handlers[0])

相关问题 更多 >