如何为log4j消息添加前缀(在对象级别) [英] How do I add a prefix to log4j messages (at the object level)

查看:1009
本文介绍了如何为log4j消息添加前缀(在对象级别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用log4j2,我想为我的所有消息添加前缀。此前缀将传递给构造函数参数,它取决于类的实例。所以我们处于对象级别(不是类或线程)。

I use log4j2 and I would like to add a prefix to all my messages. This prefix is passed to the constructor parameter and it depends on the instance of the class. So we're at the object level (not class or thread).

例如,我有一个 A 类实例化为 new A(152),所以当我在这个类上使用 log.error(message)时, 152:写在消息之前。对于新A(155),将显示 155:

For example, I have an A class instantiated like new A(152), so when I use log.error("message") on this class, 152: is written just before the message. For new A(155), 155: will be displayed instead.

感谢您的帮助

推荐答案

使用MDC来实现这个

在你的构造函数中,

 MDC.put("prefix", yourvalue);

在您的XML中使用它就像这样

and in your XML use it like this in pattern

      %X{prefix}

这篇关于如何为log4j消息添加前缀(在对象级别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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