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

2019-02-13 10:13发布

问题:

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

回答1:

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}


回答2:

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");
    }
}


回答3:

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);
    }
}


回答4:

try this

public void writeError(String msg,int intValue) {
logger.error(intValue+" "+msg);
}


回答5:

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