Pelicer
Pelicer

Reputation: 1574

Intercept requests and responses to get/add correlation id with spring boot

I'm developing a microservice and I'm trying, for the first time, to implement correlation ID. Basically I have a controller, and I would like to intercept any requests to get the correlation ID from the request header or create one, if the header is not present. I would also like to add the correlation id to the response header, as well as keep it in SLF4J MDC for logging purposes.

Currently I have:

@Slf4j
@Component
public class CorrelationIdInterceptor implements HandlerInterceptor {

    private final static String CORRELATION_ID_NAME = "correlation-id";

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        final String correlationId = getOrGenerateCorrelationId(request);
        MDC.put(CORRELATION_ID_NAME, correlationId);
        log.info("New correlation id: {}", correlationId);
        return true;
    }

    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(CORRELATION_ID_NAME);
    }

    private String getOrGenerateCorrelationId(final HttpServletRequest request) {
        final String correlationId = request.getHeaders(CORRELATION_ID_NAME).toString();
        if(correlationId.isEmpty()) {
            return UUID.randomUUID().toString();
        }
        return correlationId;
    }

}

And a web config to specify my custom interceptor as the default:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(new CorrelationIdInterceptor());
    }
}

The line log.info("New correlation id: {}", correlationId); is never called, since I can't see it in the console. I've tried also using GlobalFilter approach and couldn't make it. What am I doing wrong? How can I accomplish a correlation id interceptor and have the id logged in all my Slf4j logs?

Upvotes: 3

Views: 18816

Answers (2)

Raul Lapeira Herrero
Raul Lapeira Herrero

Reputation: 987

Are you sure the class is in a package that is being scanned for annotations? Looks like your config is complete

Upvotes: 0

Toomas Test
Toomas Test

Reputation: 40

You can use Spring Cloud Sleuth built in trace ID too. https://www.baeldung.com/spring-cloud-sleuth-single-application

Upvotes: 2

Related Questions