我正在使用日志记录(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?)
推荐答案只需实现一个 logging.Filter 的子类:docs.python/library/logging.html#filter-objects.它将有一种方法,filter(record),它检查日志记录并返回 True 以记录它或返回 False 以丢弃它.然后,您可以通过调用 addFilter(filter) 方法在 Logger 或 Handler 上安装过滤器.
Just implement a subclass of logging.Filter: docs.python/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())或者类似的东西,无论如何.
Or something like that, anyway.
更多推荐
使用过滤器记录
发布评论