Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kwon37xi
Last active July 20, 2020 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwon37xi/6e7aa448541d32faff105e5d53ab4a90 to your computer and use it in GitHub Desktop.
Save kwon37xi/6e7aa448541d32faff105e5d53ab4a90 to your computer and use it in GitHub Desktop.
Spring MVC logging controller information with MDC.
@Slf4j
public class MdcLoggingInterceptor implements HandlerInterceptor {
public static final String REQUEST_URL_MDC_KEY = "URL";
public static final String REQUEST_CONTROLLER_MDC_KEY = "Controller";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
String fullUrl = request.getRequestURI() + Optional.ofNullable(request.getQueryString()).map(qs -> "?" + qs).orElse("");
HandlerMethod handlerMethod = (HandlerMethod) handler;
String controllerInfo = handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
log.debug("Request URL: {} Controller: {}", fullUrl, controllerInfo);
MDC.put(REQUEST_URL_MDC_KEY, fullUrl);
MDC.put(REQUEST_CONTROLLER_MDC_KEY, controllerInfo);
MDC.put("URL_PATTERN", String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))); // /url/pattern/{path_var}
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.clear();
}
}
/*
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MdcLoggingInterceptor()).addPathPatterns("/**");
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment