如何将自定义字段添加到 Python 日志格式字符串? [英] How do I add custom field to Python log format string?
问题描述
我当前的格式字符串是:
formatter = logging.Formatter('%(asctime)s : %(message)s')
并且我想添加一个名为 app_name
的新字段,该字段在包含此格式化程序的每个脚本中将具有不同的值.
导入日志formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')syslog.setFormatter(格式化程序)logger.addHandler(系统日志)
但我不确定如何将 app_name
值传递给记录器以插入格式字符串.我显然可以通过每次传递它来让它出现在日志消息中,但这很混乱.
我试过了:
logging.info('日志消息', app_name='myapp')logging.info('日志消息', {'app_name', 'myapp'})logging.info('日志消息', 'myapp')
但没有用.
Python3
从 Python3.2 开始,您现在可以使用 LogRecordFactory
导入日志logging.basicConfig(format=%(custom_attribute)s - %(message)s")old_factory = logging.getLogRecordFactory()def record_factory(*args, **kwargs):记录 = old_factory(*args, **kwargs)record.custom_attribute = 我的属性";退货记录logging.setLogRecordFactory(record_factory)
<预><代码>>>>logging.info(你好")我的属性 - 你好
当然,record_factory
可以自定义为任何可调用的,如果您保留对工厂可调用的引用,则可以更新 custom_attribute
的值.
为什么这比使用适配器/过滤器更好?
- 您无需在应用程序中传递记录器
- 它实际上适用于使用自己的记录器的 3rd 方库(只需调用
logger = logging.getLogger(..)
)现在将具有相同的日志格式.(过滤器/适配器不是这种情况,您需要使用相同的记录器对象) - 您可以堆叠/链接多个工厂
My current format string is:
formatter = logging.Formatter('%(asctime)s : %(message)s')
and I want to add a new field called app_name
which will have a different value in each script that contains this formatter.
import logging
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)
But I'm not sure how to pass that app_name
value to the logger to interpolate into the format string. I can obviously get it to appear in the log message by passing it each time but this is messy.
I've tried:
logging.info('Log message', app_name='myapp')
logging.info('Log message', {'app_name', 'myapp'})
logging.info('Log message', 'myapp')
but none work.
Python3
As of Python3.2 you can now use LogRecordFactory
import logging
logging.basicConfig(format="%(custom_attribute)s - %(message)s")
old_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
record.custom_attribute = "my-attr"
return record
logging.setLogRecordFactory(record_factory)
>>> logging.info("hello")
my-attr - hello
Of course, record_factory
can be customized to be any callable and the value of custom_attribute
could be updated if you keep a reference to the factory callable.
Why is that better than using Adapters / Filters?
- You do not need to pass your logger around the application
- It actually works with 3rd party libraries that use their own logger (by just calling
logger = logging.getLogger(..)
) would now have the same log format. (this is not the case with Filters / Adapters where you need to be using the same logger object) - You can stack/chain multiple factories
这篇关于如何将自定义字段添加到 Python 日志格式字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!