如何使用logging.Filter?

2020年5月24日 / 8次阅读 / Last Modified 2020年5月24日
logging模块

在使用Filter过滤日志之前,首先要搞清除logging模块时如何记录日志的,具体请参考我的上一篇博文:logger的工作流程

关于filter部分,总结一句话:先过logger自己的filter,再过handler的filter。下面是一个示例代码,要继承logging.Filter类来创建自己的Filter对象。

import sys
import logging


class levelFilter(logging.Filter):
    def filter(self, record):
        if record.levelno < logging.WARNING:
            return False
        return True


class stringFilter(logging.Filter):
    def filter(self, record):
        if record.msg.find('abc') == -1:
            return True
        return False
        

log = logging.getLogger('test')
log.setLevel(logging.INFO)
stream_handler = logging.StreamHandler(sys.stdout)
log.addHandler(stream_handler)
log.warning('this is warning-1')
log.info('this is info-1')

log.addFilter(levelFilter())
log.warning('this is warning-2')
log.info('this is info-2')

stream_handler.addFilter(stringFilter())
log.warning('this is warning-3')
log.info('this is info-3')
log.warning('this is warning-abc')

以上代码创建了2个Filter,一个给logger用,用来过滤warning以下的日志,虽然logger自己的level是info。另一个给handler用,用来过滤含有abc字符串的日志。以上代码执行效果如下:

D:\py>python log_filter.py
this is warning-1
this is info-1
this is warning-2
this is warning-3

完全符合预期。这就是logging.Filter的用法。

最后补充一个细节,logging.Filter的代码如下,里面提到filter函数除了自己在继承类中改写外,还可以在这个地址修改record的内容,如果有必要的话。

class Filter(object):
    """
    Filter instances are used to perform arbitrary filtering of LogRecords.

    Loggers and Handlers can optionally use Filter instances to filter
    records as desired. The base filter class only allows events which are
    below a certain point in the logger hierarchy. For example, a filter
    initialized with "A.B" will allow events logged by loggers "A.B",
    "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
    initialized with the empty string, all events are passed.
    """
    def __init__(self, name=''):
        """
        Initialize a filter.

        Initialize with the name of the logger which, together with its
        children, will have its events allowed through the filter. If no
        name is specified, allow every event.
        """
        self.name = name
        self.nlen = len(name)

    def filter(self, record):
        """
        Determine if the specified record is to be logged.

        Is the specified record to be logged? Returns 0 for no, nonzero for
        yes. If deemed appropriate, the record may be modified in-place.
        """
        if self.nlen == 0:
            return True
        elif self.name == record.name:
            return True
        elif record.name.find(self.name, 0, self.nlen) != 0:
            return False
        return (record.name[self.nlen] == ".")

filter函数有默认行为,不过一般不用。

-- EOF --

本文链接:https://www.pynote.net/archives/2006

留言区

电子邮件地址不会被公开。 必填项已用*标注


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top