I am working on an application which is heavily using lombok Slf4j. I want to attach some identifier to the logs. MDC is the one which solves this problem for Slf4j but I want to use that with lombok slf4j. I searched on the net but couldn't find any resources. Is there any way or resources that would be helpful?
Asked
Active
Viewed 3,924 times
2
-
2What problem do you have? It should work just fine. Show as your code. – talex Jun 28 '18 at 08:00
-
I couldn't find the option of importing MDC (if I added lombok slf4j). If I could add that then only I can set some identifier there. – Tejas Joshi Jun 28 '18 at 09:09
1 Answers
1
It is take some configuration but what you need to do.
Put some dependency in pom.xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
configure logback.xml
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%X{x} %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Add some magic to any class
static {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
and put it all to work
@Log
public class App {
public static void main(String[] args) throws IOException {
MDC.put("x", "MDC var");
log.info("log message");
}
}
Run and enjoy your logs:
MDC var log message
special thanks to this answer

talex
- 17,973
- 3
- 29
- 66