如何使用 SL4J 在 Log4j2 上包装变量

How to wrap variable over Log4j2 with SL4J

目前,我的应用程序需要一些应附加到日志消息的值。 由于它在 SL4J 下使用 Log4J2,我的第一个想法是对 Log4J 记录器做一个包装器,我可以在其中将新值添加到输出。

一些博客指出我应该写一个 Logger、一个 LoggerFactory 和一个 Binder。但是它们已经过时了(2011 年)并且没有希望让这些代码与当前的库一起工作。

我还看到了一些关于 ThreadContext 的信息,它看起来像我想要构建此测试的内容。

所以我的问题是什么是最实用(简单)的方法来扩展日志记录机制并有一些变量我可以 put/or 通过这个包装器在日志消息的开头从 ThreadContext 恢复。

logger.info("this is a message"); // Custom logger looks the same as usual

但在内部它与一些 ThreadContext 一起工作以增加日志消息。

@Override
public void info(final String format) {
    // get some value from ThreadContext
    // add some value that not exist on ThreadContext
    // use it on format string
    // format = container_name + " - " + GUUID + " - " + format;
    logger.logIfEnabled(FQCN, Level.INFO, null, format);
}

代码

package hello;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    final static Logger logger = LoggerFactory.getLogger(SampleController.class);

    @RequestMapping("/")
    @ResponseBody
    String home() {
        logger.info("this is a message");
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }

}

输出

17:22:13.718 [http-nio-8080-exec-1] INFO  hello.SampleController - this is a message

期望输出

17:22:13.718 [http-nio-8080-exec-1] INFO  hello.SampleController - CONTAINERXPTO - 0284-8576-9376-8376 - this is a message

参考资料

http://poth-chola.blogspot.com.br/2015/08/custom-slf4j-logger-adapter.html http://binkley.blogspot.com.br/2010/12/correct-slf4j-logger-wrapping.html http://javaeenotes.blogspot.com.br/2011/12/custom-slf4j-logger-adapter.html

以下博客-post

http://veerasundar.com/blog/2009/11/log4j-mdc-mapped-diagnostic-context-example-code/

描述了一种解决方案,用于透明地向记录调用添加额外的 - 请求相关 - 信息。

编辑:

简而言之,您需要向您的 Web 应用程序添加一个 servlet 过滤器,用于根据每个请求获取您需要的信息。

在此过滤器中,您可以将信息放入称为 MDC(映射诊断上下文)/ThreadContext 的线程本地映射中。 实现可能如下所示:

public class RequestInformationFilter implements Filter {

   @Override
   public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        try {
            MDC.put("variableName", "variableValue");

            chain.doFilter(request, response);

        } finally {
            MDC.remove("variableName");
        }

    }

}

之后您可以在日志模式中使用 %X{variableName} 来打印 variableName 的值。