log4j日志中输出sessionID的方法

在web应用中,如果使用log4j做日志输出时,如果要输出sessionID,需要使用log4j的MDC或者NDC,这两者实现的功能是一样的,但是实现方法不一样,NDC使用的是HashMap,MDC使用的是线程的localThread。我是使用的MDC。

具体做法就是写一个Filter,在其中利用log4j的MDC把sessionID记录下来,然后在log4j的输出格式中利用%X输出即可。

我的Filter的代码是这样的,其中取sessionId的方法仅适用于spring框架,需要注意的是一定要在finally里把记录的数据清除掉。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
	try {
		HttpServletRequest httpReq = (HttpServletRequest)request;
		MDC.put("sessionId", httpReq.getRequestedSessionId());
			
		chain.doFilter(request, response);			
	} finally {
		MDC.clear();
	}
}

在web.xml里配置Filter就不写了哈。

log4j中的配置如下,其中%X{sessionId}就可以取到Filter里写入的sessionId

log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %t %X{sessionId} %c{2}:%L - %m%n

猜你喜欢

转载自yiyu.iteye.com/blog/2210915
今日推荐