log4j2 HTTP请求日志异步

1、首先maven项目加入依赖包

<dependency>
    <groupId>org.apache.logging.log4jgroupId>
    <artifactId>log4j-coreartifactId>
    <version>2.9.0version>
dependency>
<dependency>
    <groupId>org.apache.logging.log4jgroupId>
    <artifactId>log4j-apiartifactId>
    <version>2.9.0version>
dependency>
<dependency>
    <groupId>com.lmaxgroupId>
    <artifactId>disruptorartifactId>
    <version>3.3.4version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.0version>
dependency>

2、进行log4j2.xml文件配置。

将配置文件log4j2.xml配置到classpath下面。以下是简单的xml配置。其中apperders元素配置了Http 其实调用的就是log4j2 core包下org.apache.logging.log4j.core.appender.HttpAppender这个处理类


<configuration>
    <appenders>
        <Http name="Http" url="http://localhost:29010/compass/log">
            <JsonLayout properties="true"/>
        Http>
    appenders>

    <loggers>
        
        
        <Logger name="com.spring.mvc" level="error" additivity="true">
            <AppenderRef ref="Http"/>
        Logger>
    loggers>
configuration>

通过以上配置则实现了http日志请求。

3、properties配置文件实现异步

同样在classpath下面加入log4j2.component.properties配置文件添加以下配置

Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

也可以在代码中将其加上系统配置如:

        System.setProperty("Log4jContextSelector","org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

以下是业务调用日志输出

private static Logger log=LogManager.getLogger(LogController.class);

@RequestMapping("/log")
String log() {

    log.info("info test");

    log.warn("warn test");

    log.error("error test");

    return "ok";
}

如果没有这个系统配置。业务当中调用的这个Logger对象将是
org.apache.logging.log4j.core.Logger
加上了这个系统配置则Logger对象是
org.apache.logging.log4j.core.async.AsyncLogger

4、日志信息

以下是日志服务器也就是log4j2.xm所配置的http://localhost:29010/compass/log这台日志服务所接收到的json日志

{
  "timeMillis" : 1507620120885,
  "thread" : "http-nio-8081-exec-2",
  "level" : "ERROR",
  "loggerName" : "com.spring.mvc.web.controller.LogController",
  "message" : "error test",
  "endOfBatch" : true,
  "parameterCount" : 0,
  "formattedMessage" : "error test",
  "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
  "threadPriority" : 5,
  "threadId" : 50,
  "contextMap" : { }
}

你可能感兴趣的:(mybatis,logback)