How do I add a prefix to log4j messages (at the ob

2019-02-13 09:37发布

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).

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.

Thanks for your help

5条回答
ゆ 、 Hurt°
2楼-- · 2019-02-13 09:57

One solution is a wrapper class.

public class YourLogger
{
    private Logger log;

    public void error(int value, String msg)
    {
        log.error(String.valueOf(value) + ": " + msg);
    }
}
查看更多
萌系小妹纸
3楼-- · 2019-02-13 10:00

Based on Bill Clars answer:

public class LogWrapper
{
    private Logger log;
    private String prefix;

    public LogWrapper(Logger log, String prefix) {
        this.log = log;
        this.prefix = prefix;
    }

    public void error(String msg)
    {
        log.error(prefix + ": " + msg);
    }
}

Then you set as instance variable in your class

public class MyClass {
    private LogWrapper log;

    public MyClass(int prefix) {
        log = new LogWrapper(Logger.getLogger(this.getClass()), String.valueOf(prefix));

        // then log away
        log.error("Test");
    }
}
查看更多
Bombasti
4楼-- · 2019-02-13 10:04

try this

public void writeError(String msg,int intValue) {
logger.error(intValue+" "+msg);
}
查看更多
\"骚年 ilove
5楼-- · 2019-02-13 10:10

Here is one simple workaround solution: you can wrap the string with a method that adds the prefix to it and returns concatenated string to the error method.

public class A {
    private static final Logger LOG = LogManager.getLogger();

    final int index;

    public A(int index) {
        this.index = index;
    }

    public static void f(String message) {
        return String.valueOf(index) + ": ";
    }

    public void method() {

        // ...

        LOG.error(f("message"));

    }

}

Advantages:

  • Simple
  • You can log messages with and also without the prefix in one class/method
  • You don't have to permanently add something like %X{prefix} to the log4j2 configuration

Disadvantages:

  • You always have to use the wrapper method if you want to add the prefix
查看更多
倾城 Initia
6楼-- · 2019-02-13 10:11

Use MDC to achive this

In your constructor put

 MDC.put("prefix", yourvalue);

and in your XML use it like this in pattern

      %X{prefix}
查看更多
登录 后发表回答