向日志添加自定义信息的最佳方法 [英] Best way to add custom information to for logging

查看:45
本文介绍了向日志添加自定义信息的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Python 记录文档,它当然具有很多功能……适用于一切.

I've been reading the Python logging documentation, and its certainly has a lot of functionality...for everything.

我面临的问题是我不是荷兰人,所以我不确定这样做的正确方法是什么.

The problem I'm facing is that I'm not Dutch and so I'm not sure what the right way to do this is.

我正在模拟器中运行事件,并且我想为每个日志消息添加 simulated 时间的时间戳(可能还使用了长度格式化程序,只是为了使其看起来更好).我可以在 Logger Handler 的子类中更改此设置,但我认为这不是正确的方法.

I am running events in a simulator, and I would like to prefix every log message with the timestamp of the simulated time (probably with a length formatter too, just to keep it looking good). I could change this in a subclass of Logger or Handler, but I don't think that is the right way.

我认为正确的方法是使用 LoggerAdapter Filter .是这样吗?如果是这样,我该选择哪一个呢?

I think the right way is to use a LoggerAdapter or a Filter. Is this right, and if so, which one should I prefer?

推荐答案

当然,如果您只需要为每个日志消息加上时间戳作为前缀,那么您所要做的就是为格式化程序提供适当的格式字符串吗?如此处文档.

Surely if you just need to prefix every log message with the timestamp, all you need to do is provide an appropriate format string for a formatter? As mentioned here in the documentation.

更新: LoggerAdapter 更适合于上下文信息存在时间较长的情况.例如,在处理多个客户端连接的网络服务器应用程序中,连接详细信息(例如客户端IP地址)可能是有用的上下文,因此,当创建新的客户端连接时,您将创建一个 LoggerAdapter 实例.这听起来不像您的模拟场景.

Update: A LoggerAdapter would be more appropriate for situations where contextual information is moderately long-lived. For example, in a network server application which handles multiple client connections, the connection details (e.g. client IP address) might be useful context, so you would create a LoggerAdapter instance when a new client connection was created. This doesn't sound like your simulation scenario.

另一方面,如果您可以使用 Filter 来获取模拟时间,则可以使用

A Filter, on the other hand, could be used if you could use it to get the simulation time, e.g.

class SimulationFilter(logging.Filter):
    def __init__(self, context):
        """
        Set up with context passed in which allows access
        to simulation times.
        """
        self.context = context

    def filter(self, record):
        "Add sim_time field to record, formatted as you wish"
        record.sim_time = '%s' % self.context.get_sim_time()
        return True

,然后在 Formatter 的格式字符串中添加%(sim_time)s .

and then add %(sim_time)s in your Formatter's format string.

或者,如果您每次进行记录调用时都知道模拟时间,则可以例如进行

Alternatively, if you know the simulation time whenever you make a logging call, you could just do e.g.

logger.debug('Message with %s', arguments, extra={'sim_time': sim_time})

,并且在 Formatter 的格式字符串中也有%(sim_time)s .

and likewise have %(sim_time)s in your Formatter's format string.

这篇关于向日志添加自定义信息的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆