如何在Python模块中正确添加自定义日志记录过滤器 [英] How to properly add custom logging filters in Python modules

查看:373
本文介绍了如何在Python模块中正确添加自定义日志记录过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在macOS Sierra下的Python 2.7.12中运行以下代码段,但得到KeyError s:

I'm running the following snippet in Python 2.7.12 under macOS Sierra but I get KeyErrors:

import logging
from PIL import Image


class TaskAddingFilter(logging.Filter):
    def __init__(self):
        logging.Filter.__init__(self)

    def filter(self, record):
        record.args = record.args + ('task', '')


logging.basicConfig(
    filename='mylog.txt',
    format='%(asctime)-19.19s|%(task)-36s|%(levelname)s:%(name)s:%(lineno)s: %(message)s',
    level=eval('logging.%s' % 'DEBUG'))

# My attempt to "monkey-patch" PIL's logger 
for name, logger in logging.Logger.manager.loggerDict.iteritems():
    logger = logging.getLogger(name)
    if name.startswith('PIL'):
        logger.addFilter(TaskAddingFilter())

logger = logging.getLogger('demo')


def tryThis():
    with open('my_image.png', 'rb') as im:
        logger.debug('Attempting to read image size...', extra={'task': '123'})
        try:
            image = Image.open(im)
            w, h = image.size
            image.save('my_image_out.png', 'PNG')
        except IOError:
            logger.error('Processing failed!', extra={'task': '123'})
            raise Exception()


tryThis()

我得到的错误是:

Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'task'
Logged from file PngImagePlugin.py, line 135

有什么想法吗?

提前谢谢.

推荐答案

更好的解决方案是显式添加所需的处理程序(而不是使用basicConfig())并将过滤器附加到它们.这样就无需修补PIL(或任何其他)记录器,也无需将extra传递给记录调用.过滤方法只需要设置

A better solution would be to explicitly add the handlers you want (rather than using basicConfig()) and attach the filter to them. Then there's no need to patch PIL (or any other) loggers, nor to pass extra to logging calls. The filter method just needs to set

record.task = 'foo'

而不是弄乱record.args.

这篇关于如何在Python模块中正确添加自定义日志记录过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆