我需要使用jboss logger和logstash改进在wildfly上运行的JavaEE应用程序的日志记录,我正在使用MDC来存储用户ID,但是由于我是线程使用的新手,我不知道如何在线程之前清除MDC回收的
我找到了清除 MDC 的不同方法,但我认为我缺少一些关于线程的知识......:我试图扩展 Thread:
public class MdcThread extends Thread {
LoggingTools loggingTools = new LoggingTools(MdcThread.class);
@Override
public void run() {
loggingTools.info("MdcThread");
MDC.clear();
}
}
我试图扩展 ThreadPoolExecutor :
public class MdcThreadPoolExecutor extends ThreadPoolExecutor {
static LoggingTools loggingTools = new LoggingTools(MdcThreadPoolExecutor.class);
...constructors...
@Override
public void execute(Runnable command) {
super.execute(wrap(command));
}
public static Runnable wrap(final Runnable runnable) {
return new Runnable() {
@Override
public void run() {
try {
runnable.run();
} finally {
loggingTools.info("Mdc clear");
MDC.clear();
}
}
};
}
}
但是这些都没有被调用......所以我认为 ThreadPoolExecutor 是一种使用线程但不一定使用的方式?我怎样才能达到线程的生命周期?
编辑:这是我使用的过滤器:
@WebFilter("/*")
public class MdcFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request != null) {
//add what I want in MDC
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
MDC.clear();
}
}