我希望能够在我的服务器上调试特定请求。 我已经跟踪了KC Baltz在Conditional logging with log4j上的回复,将感兴趣的请求记录到他们自己的日志文件中。
开始处理请求时:
FileAppender fileAppender = new FileAppender(new PatternLayout(pattern), logFileName, true);
fileAppender.setName(sessionId);
fileAppender.setThreshold(Level.TRACE);
// Add a filter to identify logs belonging to the current thread
fileAppender.addFilter(new MyCustomFilter(sessionId));
Logger.getRootLogger.addAppender(fileAppender);
// Use log4j MDC to identify logs
MDC.put("log-key", sessionId);
然后在请求完成后处理:
Appender appender = Logger.getRootLogger().getAppender(sessionId);
Logger.getRootLogger().removeAppender(appender);
MDC.remove("log-key");
相应的过滤器:
public class MyCustomFilter extends Filter {
private final String id;
public MyCustomFilter(String id) {
this.id = id;
}
@Override
public int decide(LoggingEvent event) {
Object mdc = event.getMDC("log-key");
if (id.equals(mdc)) {
return Filter.ACCEPT;
}
return Filter.DENY;
}
}
问题是根记录器的级别设置为“WARN”,我想获取给定sessionId的所有日志(TRACE级别)。