如何在python中使用相同的日志记录处理程序使用不同的格式化程序 [英] How to use different formatters with the same logging handler in python
问题描述
是否可以使用多个记录器(即logging.getLogger("base.foo")
和logging.getLogger("base.bar")
)登录到单个目的地(即使用一个FileHandler
),并为每个记录器使用不同的格式化程序.
Is it possible to log to a single destination (i.e. using one FileHandler
) with multiple loggers (i.e. logging.getLogger("base.foo")
and logging.getLogger("base.bar")
), and use different formatters for each of the loggers.
据我了解,只能为每个句柄分配一个格式化程序.也许可以将格式化程序与记录器而不是处理程序相关联吗?
To my understanding it's only possible to assign one formatter to each handle. Maybe it's possible to associate the formatter with a logger rather than the handler?
推荐答案
基于record.name
可以很容易地将其分发给不同的格式化程序.以下是概念验证的示例代码:
It's easy to dispatch to different formatters based on record.name
. Below is prove-of-concept sample code:
import logging
class DispatchingFormatter:
def __init__(self, formatters, default_formatter):
self._formatters = formatters
self._default_formatter = default_formatter
def format(self, record):
formatter = self._formatters.get(record.name, self._default_formatter)
return formatter.format(record)
handler = logging.StreamHandler()
handler.setFormatter(DispatchingFormatter({
'base.foo': logging.Formatter('FOO: %(message)s'),
'base.bar': logging.Formatter('BAR: %(message)s'),
},
logging.Formatter('%(message)s'),
))
logging.getLogger().addHandler(handler)
logging.getLogger('base.foo').error('Log from foo')
logging.getLogger('base.bar').error('Log from bar')
logging.getLogger('base.baz').error('Log from baz')
另一种方法是手动打开文件,并使用不同的格式化程序从中创建两个流处理程序.
Another way is to open file manually and create two stream handlers from it with different formatters.
这篇关于如何在python中使用相同的日志记录处理程序使用不同的格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!