将信息添加到Python日志记录中的每个日志消息中 [英] Add information to every log message in Python logging

查看:40
本文介绍了将信息添加到Python日志记录中的每个日志消息中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Python与日志记录模块一起使用,并想将socket.hostname()添加到每条日志消息中,我必须对每条消息都运行此查询,并且不能使用

I am using Python with logging module and would like to add the socket.hostname() to every log message, I have to run this query every message and can not use

name = socket.hostname() 

,然后以名称

我正在研究使用日志记录过滤器的这个示例,但是我在这里需要的不是过滤器,它是对每个日志消息的简单操作.

I am looking into this example of using logging filter, But what I need here is not a filter, it is a simple manipulation of every log message.

我如何获得想要的结果?

How can I achieve the wanted outcome?

推荐答案

您可以使用过滤器向每条消息添加信息:

You can use filter to add information to every message :

import logging
import socket

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.hostname = socket.gethostname() 
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s hostname: %(hostname)-15s : %(message)s')
    a1 = logging.getLogger('a.b.c')
    f = ContextFilter()
    a1.addFilter(f)
    a1.debug('A debug message')

这篇关于将信息添加到Python日志记录中的每个日志消息中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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