[英]Using three version (class, function, lambda) for setting logging Filter
I can create the same Filter in three different ways:我可以通过三种不同的方式创建相同的过滤器:
1) As a lambda: 1)作为一个lambda:
import logging
handler = logging.StreamHandler()
handler.addFilter(lambda record: getattr(record, 'msg') == 'Hello')
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.warning('ok!')
2) As a function: 2)作为一个函数:
def is_hello(record):
return getattr(record, 'msg') == 'Hello'
import logging
handler = logging.StreamHandler()
handler.addFilter(is_hello)
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.warning('ok!')
3) As a class 3) 作为一个班级
class LogFilter:
def filter(self, record):
return getattr(record, 'msg') == 'Hello'
import logging
handler = logging.StreamHandler()
handler.addFilter(LogFilter())
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.warning('ok!')
How does the loggin module allow such variation, does the filter do something like:登录模块如何允许这种变化,过滤器是否执行以下操作:
if callable(provider_filter):
provider_filter(record)
else:
provider_filter.filter(record)
Or how does it 'know' whether to call the function or to call one of the class methods?或者它如何“知道”是调用函数还是调用类方法之一?
Basically, yeah, it just checks if it has a .filter
attribute, and if it doesn't it assumes it's a callable:基本上,是的,它只是检查它是否具有.filter
属性,如果没有,则假定它是可调用的:
Here is the source code : 这是源代码:
def filter(self, record):
"""
Determine if a record is loggable by consulting all the filters.
The default is to allow the record to be logged; any filter can veto
this and the record is then dropped. Returns a zero value if a record
is to be dropped, else non-zero.
.. versionchanged:: 3.2
Allow filters to be just callables.
"""
rv = True
for f in self.filters:
if hasattr(f, 'filter'):
result = f.filter(record)
else:
result = f(record) # assume callable - will raise if not
if not result:
rv = False
break
return rv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.