Created
July 13, 2025 17:14
-
-
Save arleighdickerson/8a7eb08f368408cb09306ce3536a7b02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.arleigh.gantry.util.UuidGenerator; | |
import lombok.RequiredArgsConstructor; | |
import org.slf4j.MDC; | |
import org.springframework.context.annotation.Profile; | |
import org.springframework.lang.NonNull; | |
import org.springframework.stereotype.Component; | |
import org.springframework.web.filter.OncePerRequestFilter; | |
import javax.servlet.FilterChain; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import java.io.IOException; | |
import java.util.UUID; | |
@Profile("!prod") // infrastructure does it for us in production | |
@Component | |
@RequiredArgsConstructor | |
class CorrelationIdFilter extends OncePerRequestFilter { | |
public static final String REQUEST_HEADER_NAME = "X-Request-Id"; | |
public static final String ATTRIBUTE_NAME = "RequestCorrelation.ATTRIBUTE"; | |
public static final String LOG_VARIABLE_NAME = "correlationId"; | |
@Override | |
protected void doFilterInternal( | |
@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { | |
String correlationId = request.getHeader(REQUEST_HEADER_NAME); | |
if (correlationId == null || !UuidGenerator.isValidUUID(correlationId)) { | |
correlationId = UUID.randomUUID().toString(); | |
} | |
request.setAttribute(ATTRIBUTE_NAME, correlationId); | |
try (MDC.MDCCloseable ignored = MDC.putCloseable(LOG_VARIABLE_NAME, correlationId)) { | |
response.setHeader(REQUEST_HEADER_NAME, correlationId); | |
filterChain.doFilter(request, response); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment