我创建了一个具有特定日志处理程序的上下文管理器,用户可以将其添加到自己选择的日志记录器中
以下是上下文代码:# 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已从所有记录器中删除
with
中的所有代码包装在try...finally
中,但如果不利用我的上下文管理器,那就很烦人了李>__exit__
中的del self.loghandler
并不会从所有处理程序列表中删除实际对象李>logging.shutdown(self.loghandler)
不起作用李> 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)
难道没有更有效的解决方案吗?像是引用相关记录器的处理程序属性
您可以尝试以这种方式删除所有处理程序-ref:
相关问题 更多 >
编程相关推荐