How to add a prefix to log4j messages (at the object level)

I am using log4j2 and I would like to add a prefix to all my posts. This prefix is ​​passed to the constructor parameter and depends on the class instance. So, we are at the object level (not a class or stream).

For example, I have a class A created as new A(152) , so when I use log.error("message") for this class, 152: written immediately before the message. Instead of new A(155) , 155: will be displayed.

thanks for the help

+7
source share
5 answers

Use MDC to achieve this.

In your constructor put

  MDC.put("prefix", yourvalue); 

and in your XML use it in the template

  %X{prefix} 
+6
source

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 the 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
source

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

try it

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

Here is one simple solution: you can wrap a string using a method that adds a prefix to it and returns a 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")); } } 

Benefits:

  • Plain
  • You can register messages with and without prefix in one class / method
  • You do not need to constantly add something like %X{prefix} to the log4j2 configuration

Disadvantages:

  • You always need to use the shell method if you want to add a prefix
0
source

All Articles