1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.helpers;
15
16 import java.io.IOException;
17
18 import jakarta.servlet.Filter;
19 import jakarta.servlet.FilterChain;
20 import jakarta.servlet.FilterConfig;
21 import jakarta.servlet.ServletException;
22 import jakarta.servlet.ServletRequest;
23 import jakarta.servlet.ServletResponse;
24 import jakarta.servlet.http.HttpServletRequest;
25
26 import org.slf4j.MDC;
27
28 import ch.qos.logback.classic.ClassicConstants;
29
30
31
32
33
34
35
36
37
38
39 public class MDCInsertingServletFilter implements Filter {
40
41 public void destroy() {
42
43 }
44
45 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
46 throws IOException, ServletException {
47
48 insertIntoMDC(request);
49 try {
50 chain.doFilter(request, response);
51 } finally {
52 clearMDC();
53 }
54 }
55
56 void insertIntoMDC(ServletRequest request) {
57
58 MDC.put(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY, request.getRemoteHost());
59
60 if (request instanceof HttpServletRequest) {
61 HttpServletRequest httpServletRequest = (HttpServletRequest) request;
62 MDC.put(ClassicConstants.REQUEST_REQUEST_URI, httpServletRequest.getRequestURI());
63 StringBuffer requestURL = httpServletRequest.getRequestURL();
64 if (requestURL != null) {
65 MDC.put(ClassicConstants.REQUEST_REQUEST_URL, requestURL.toString());
66 }
67 MDC.put(ClassicConstants.REQUEST_METHOD, httpServletRequest.getMethod());
68 MDC.put(ClassicConstants.REQUEST_QUERY_STRING, httpServletRequest.getQueryString());
69 MDC.put(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY, httpServletRequest.getHeader("User-Agent"));
70 MDC.put(ClassicConstants.REQUEST_X_FORWARDED_FOR, httpServletRequest.getHeader("X-Forwarded-For"));
71 }
72
73 }
74
75 void clearMDC() {
76 MDC.remove(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY);
77 MDC.remove(ClassicConstants.REQUEST_REQUEST_URI);
78 MDC.remove(ClassicConstants.REQUEST_QUERY_STRING);
79
80 MDC.remove(ClassicConstants.REQUEST_REQUEST_URL);
81 MDC.remove(ClassicConstants.REQUEST_METHOD);
82 MDC.remove(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY);
83 MDC.remove(ClassicConstants.REQUEST_X_FORWARDED_FOR);
84 }
85
86 public void init(FilterConfig arg0) throws ServletException {
87
88 }
89 }