用过滤器记录 [英] logging with filters
问题描述
我正在使用日志记录(import logging
)记录消息.
I'm using Logging (import logging
) to log messages.
在1个单个模块中,我以调试级别my_logger.debug('msg')
记录消息;
Within 1 single module, I am logging messages at the debug level my_logger.debug('msg')
;
其中一些调试消息来自function_a()
,而其他消息则来自function_b()
;我希望能够基于它们是来自a还是来自b来启用/禁用日志记录;
Some of these debug messages come from function_a()
and others from function_b()
; I'd like to be able to enable/disable logging based on whether they come from a or from b;
我猜想我必须使用Logging的过滤机制.
I'm guessing that I have to use Logging's filtering mechanism.
有人可以告诉我如何使用下面的代码来完成我想做的事情吗?
Can someone show me how the code below would need to be instrumented to do what I want?
import logging
logger= logging.getLogger( "module_name" )
def function_a( ... ):
logger.debug( "a message" )
def function_b( ... ):
logger.debug( "another message" )
if __name__ == "__main__":
logging.basicConfig( stream=sys.stderr, level=logging.DEBUG )
#don't want function_a()'s noise -> ....
#somehow filter-out function_a's logging
function_a()
#don't want function_b()'s noise -> ....
#somehow filter-out function_b's logging
function_b()
如果我将这个简单的示例扩展到更多的模块和每个模块更多的功能,我会担心很多记录器;
If I scaled this simple example to more modules and more funcs per module, I'd be concerned about lots of loggers;
我可以将每个模块的记录器数量减少到1个吗?请注意,日志消息是结构化的",即,如果记录日志的函数正在执行某些解析工作,则它们都包含前缀logger.debug("parsing: xxx")
-我可以用单行以某种方式关闭所有解析"消息(不管发出消息的模块/功能是什么?)
Can I keep it down to 1 logger per module? Note that the log messages are "structured", i.e. if the function(s) logging it are doing some parsing work, they all contain a prefix logger.debug("parsing: xxx")
- can I somehow with a single line just shut-off all "parsing" messages (regardless of the module/function emitting the message?)
推荐答案
Just implement a subclass of logging.Filter
: http://docs.python.org/library/logging.html#filter-objects. It will have one method, filter(record)
, that examines the log record and returns True to log it or False to discard it. Then you can install the filter on either a Logger
or a Handler
by calling its addFilter(filter)
method.
示例:
class NoParsingFilter(logging.Filter):
def filter(self, record):
return not record.getMessage().startswith('parsing')
logger.addFilter(NoParsingFilter())
还是这样.
这篇关于用过滤器记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!