Reputation: 5048
I need to make my logs (log4j engine) to be more informative with a unique id per request for my REST API in Spring-Boot application.
I want to avoid using a superclass which got requestId field and extend from it.
I tried to look for a good example over the web, but it wasn't so clear.
Is there any best practice that I can use?
Upvotes: 2
Views: 9848
Reputation: 1193
There are several best practices used as follows:
Upvotes: 0
Reputation: 26572
Using a field for such a feature would just cause problems during the integration testing on the first glance..
Ideally, just follow an SRP principle and include the generation logic inside a dedicated class which you could make an injectable @Component
.. MyIdGenerator
etc.
There you could have a synchronized method generateId()
.
Now you could use it in whichever controller it is needed and also you could set-up your integration test more easily and have more control over them.
Update:
You could take also advantage of HandleInterceptorAdapter
if this should be a global strategy:
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/* generate unique id here and log what is needed */
}
You can encapsulate the ID generation and logging inside this class.
Upvotes: 1