I use SpringBoot app. Every request has ID. And I has to use this ID when log errors in some services and more lowlevel places of the program. How can I implement it? Thank you!
Asked
Active
Viewed 1,594 times
0
-
you can use `@RequestParam` or `@Pathvariable` – Amol Raje Dec 08 '17 at 14:38
2 Answers
0
For adding a context id to you log you can use the MDC :
in your code :
MDC.put("first", "Dorothy");
in your logback.xml
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout>
<Pattern>%X{first} %X{last} - %m%n</Pattern>
</layout>
</appender>

Arnaud
- 51
- 3
0
You can use ThreadLocal to store that ID for a specific Thread.
Then, in your services you can get that ID throghtout the method ThreadLocal#get
.
For example (This is just an approach):
class AppProvider {
public static final ThreadLocal<String> APP_CONTEXT = new ThreadLocal<String>();
}
class Controller {
public void users(@RequestParam String id) {
AppProvider.APP_CONTEXT.set(id);
.......
}
}
class Service {
try {
} catch (Exception e) {
log.error(String.format("Id: %s", AppProvider.APP_CONTEXT.get()));
}
}
This is just an approach using ThreadLocal.
Look a this for Memory leak handling: https://stackoverflow.com/a/17975255/1715121

Ele
- 33,468
- 7
- 37
- 75