I am working on a java spring boot application made through maven.
Suppose my pom.xml has version 2.1.205.
I want it to put into slf4j MDC, so that with every log being printed, my version of current build should be printed.
I am working on a java spring boot application made through maven.
Suppose my pom.xml has version 2.1.205.
I want it to put into slf4j MDC, so that with every log being printed, my version of current build should be printed.
First, make sure you generate a jar with a properties file exposing the version number in it, as in this answer.
Then, following "Use MDC (Mapping Diagnostic Context) in your log" from Moulin Raphaël, define a pattern layout in your src/main/resources/log4j2.xml
<PatternLayout pattern="%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{%X}{faint} %clr{:}{faint} %m%n%xwEx"> </PatternLayout>
This Map is displayed in the logs if the
%X
mask is used in the Log4j message format definition.
This is the case here in oursrc/main/resources/log4j2.xml
file.
Write a CommandLineRunner which will put the right value in your loglogger.
package com.yourapp.mdc;
...
import org.slf4j.MDC;
@Component
public class Execute implements CommandLineRunner {
...
public void run(String... args) {
MDC.put("Version", "Version as read from properties file");
log.info("Test Log4j with MDC");
}
}
You can use that logger elsewhere with:
private static final Logger log = LoggerFactory.getLogger(Example.class);