我正在尝试为每个日志添加用户名。我发现 MDC 是合适的解决方案,我遵循了该教程。
这是一个日志片段,用于测试目的;我打印单词“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
如您所见,它似乎只在Struts2 拦截器或操作中有效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?
编辑:
我添加了一个日志,这样我就可以看到地图中的数据何时被删除。在第一个动作/拦截器日志之前,它们在地图中什么都没有。我希望看到这样的东西:
- AuthenticationFilter - 测试 -
- 拦截器日志
- AuthenticationFilter 用户名已删除