[英]Spring Boot Filter not filtering all my logs
我在 Spring Boot 应用程序中设置了一个过滤器来向 MDC 添加一些信息:
@Component
public class LogFilter implements Filter {
@Override
public void init(FilterConfig var1) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
MDC.put("tag", "Some information);
chain.doFilter(request, response);
} finally {
MDC.clear();
}
}
@Override
public void destroy() { }
}
这对于我的大多数应用程序来说都很好,但是对于生成线程的某些操作,此过滤器不会接收这些消息。
例如,在下面的块中,回调方法发生在一个单独的线程中,所以第一个log.info
调用被我的LogFilter
,但我的回调中的log.info
和log.error
不是。
private void publishMessage(String message) {
log.info("Message received. Sending to Kafka topic");
CompletableFuture<ListenableFuture<SendResult<String, String>>> future = CompletableFuture.supplyAsync(() -> kafkaTemplate.send("myTopic", message));
try {
future.get().addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
log.info("Kafka topic " + myTopic + " published to successfully");
}
@Override
public void onFailure(Throwable ex) {
log.error("Kafka error: " + ex.getMessage());
}
});
} catch (Exception e) {
log.error("Kafka has failed you for the last time");
}
}
一般来说,似乎没有在http-nio-8080-exec-X
线程之一中发生的任何日志事件都会绕过LogFilter
。 我究竟做错了什么?
我尝试过但没有奏效的事情:
LogFilter
延长GenericFilterBean
,使用@Bean
代替@Component
,然后注册这个bean与FilterRegistrationBean
在我的主应用程序类@WebFilter(urlPatterns = {"/*"}, description = "MDC Filter")
和/或@ServletComponentScan
MDC 上下文仅适用于当前正在运行的线程,但您的回调将在不同的线程中调用。
处理它的一种方法是实现ListenableFutureCallback
:
private static class MyListenableFutureCallback
implements ListenableFutureCallback<SendResult<String, String>> {
private Map<String,String> contextMap = MDC.getCopyOfContextMap();
@Override
public void onSuccess(SendResult<String, String> result) {
MDC.setContextMap(contextMap); //add MDC context here
log.info("Kafka topic " + myTopic + " published to successfully");
}
@Override
public void onFailure(Throwable ex) {
MDC.setContextMap(contextMap); //add MDC context here
log.error("Kafka error: " + ex.getMessage());
}
}
最后:
future.get().addCallback(new MyListenableFutureCallback()).
这里描述了一种更一致的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.