我正在尝试为每个日志添加用户名。我发现MDC是适当的解决方案,我遵循that tutorial。
这是一个日志片段,用于测试目的;我打印“TEST”而不是用户名:
2013-09-30 11:24:03,087 INFO company.filter.AuthenticationFilter - TEST - AuthenticationFilter is called
2013-09-30 11:24:03,089 INFO company.filter.AuthenticationFilter - TEST - userName is removed
2013-09-30 11:24:03,089 INFO company.filter.AuthenticationFilter - TEST - AuthenticationFilter is called
2013-09-30 11:24:03,089 INFO company.filter.AuthenticationFilter - TEST - userName is removed
2013-09-30 11:24:03,093 INFO company.interceptors.AuthentificationInterceptor - - Interceptor, actionName : Company_getTab redirect to Login_timeOut : false
2013-09-30 11:24:03,094 INFO company.interceptors.AuthentificationInterceptor - - Interceptor, actionName : Company_getTop redirect to Login_timeOut : false
2013-09-30 11:24:03,095 INFO company.interceptors.AuthentificationInterceptor - - Interceptor, actionName : Company_getBottom redirect to Login_timeOut : false
2013-09-30 11:24:03,124 INFO company.actions.CompanyAction - - sample log
正如您所看到的,它似乎仅在AuthenticationFilter
中起作用,但在Struts2拦截器或动作中起作用。我用这种方式实现了AuthenticationFilter
:
public class AuthenticationFilter implements Filter {
private final Logger logger = Logger.getLogger(AuthenticationFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
MDC.put("userName", "TEST");
logger.info("AuthenticationFilter is called");
chain.doFilter(request, response);
} finally {
logger.info("userName is removed.");
MDC.remove("userName");
}
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
我将其添加到文件web.xml
:
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>company.filter.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这就是我在log4j.xml
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %c - %X{userName} - %m%n"/>
</layout>
我想有些东西我不了解MDC。我认为每个请求都会调用MDC,因此可以设置ThreadLocal
的映射,每个请求都有自己的线程(我可能也不理解ThreadLocal
。)。
我应该查找/修改哪些内容,以便在配置中使用MDC?
编辑:
我添加了一个日志,这样我就可以看到地图中的数据被删除的时间。在第一个动作/拦截器日志之前,它们在地图中没有任何内容。我希望看到这样的事情: