Last active
July 20, 2020 17:31
-
-
Save kwon37xi/6e7aa448541d32faff105e5d53ab4a90 to your computer and use it in GitHub Desktop.
Spring MVC logging controller information with MDC.
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
@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