公司项目Log4j使用MDC记录sessionid

编程

具体原理这里不再详述。三个地方加上配置即可。

web.xml

	<!-- Log4j日志过滤器 -->

<filter>

<filter-name>log4jFilter</filter-name>

<filter-class>com.citicpru.imobile.web.filter.Log4jFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>log4jFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

log4j filter

public class Log4jFilter implements Filter {

private final static Logger logger = Logger.getLogger(Log4jFilter.class);

private final static String SESSION_ID="sessionId";

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

String logid = "",sessionId="";

try {

logid = ECSStringUtils.getUUID();

HttpSession session=httpServletRequest.getSession(false);

sessionId=session==null?"":session.getId();

MDC.put("logid", logid);

MDC.put(SESSION_ID, sessionId);

chain.doFilter(request, response);

} catch (Exception e) {

logger.error("执行Log4j过滤器拦截到Controller执行失败,logid: " + logid, e);

throw new ServletException(e);

} finally {

Map<?, ?> map = MDC.getContext();

if (map != null) {

map.clear();

}

}

}

@Override

public void destroy() {

}

}

配置,留意常量

#%m 输出代码指定消息

#%p 输出优先级

#%r 输出自应用启动到输出到该log信息耗时毫秒数

#%c 输出所属类全名

#%t 输出产生该日志的线程名

#%n 输出一个回车换行符 window为rn linux 为n

#%d 输出日志时间点的日期 %d{yyyy-mm-dd hh:mm:ss}

#%l 输出日志时间发生的位置 包括 类目名,线程以及代码中的行数

#Console Appender

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.Threshold=info

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=[%p] [%d] [logid:%X{logid}] [sessionId:%X{sessionId}] %l -%m%n

#RollingFile Appender(Store Application Message, Hourly Rolling, Threshold is INFO)

log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender

log4j.appender.RollingFile.File=/webapp/iecs/imobile/log/i-mobile.log

log4j.appender.RollingFile.Threshold=info

log4j.appender.RollingFile.File.DatePattern=.yyyy-MM-dd-HH

log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout

log4j.appender.RollingFile.layout.ConversionPattern=[%p] [%d] [logid:%X{logid}] [sessionId:%X{sessionId}] %l -%m%n

 

 

以上是 公司项目Log4j使用MDC记录sessionid 的全部内容, 来源链接: utcz.com/z/511676.html

回到顶部