Last active
August 29, 2015 14:01
-
-
Save flurrydev/77b27c9bbcc926f44a2b to your computer and use it in GitHub Desktop.
LogRequestFilter Sample Code
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 javax.servlet.*; | |
import javax.servlet.http.HttpServletRequest; | |
public class LogRequestFilter implements Filter | |
{ | |
public static final String kDebugHeaderName = "DEBUG"; | |
private final static ThreadLocal<String> threadLocalLoggingTag = new ThreadLocal<String>(); | |
/* Nothing needed in init/destroy methods for the javax Filter interface. Just included for completeness */ | |
@Override public void init(FilterConfig config) { } | |
@Override public void destroy() { } | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException | |
{ | |
try { | |
String loggingKey = ((HttpServletRequest) request).getHeader(kDebugHeaderName); | |
// If a special header is present, we will tag this thread to start logging. | |
if(loggingKey != null && !loggingKey.isEmpty()) { | |
startLogging(loggingKey); | |
} | |
chain.doFilter(request, response); | |
} finally { | |
// Be sure to close out logging once this thread is finished processing the request. | |
endLogging(); | |
} | |
} | |
public void startLogging(String loggingKey) | |
{ | |
// Only set the tag if one is not already present. | |
// Note: You can also enforce a strict check to only allow logging when this Filter's doFilter method has been called. | |
// This would ensure that the DEBUG logging can only be called on request threads which will automatically call endLogging | |
// The stricter check is not included in this sample for brevity. | |
if(threadLocalLoggingTag.get() == null) { | |
threadLocalLoggingTag.set(loggingKey); | |
} | |
} | |
private void endLogging() | |
{ | |
threadLocalLoggingTag.remove(); | |
} | |
public static String getLoggingKey() | |
{ | |
return threadLocalLoggingTag.get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment