spring boot下使用logback或log4j生成符合Logstash标准的JSON格式

使用logback

1.引入logstash日志格式支持

<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>4.4</version>
</dependency>

2.在spring boot的配置文件application.properties指定使用logback.xml位置

logging.config=config/logback.xml

3.在logback.xml中添加用来记录logstash的appender

<appender name="LOGSTASH" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <charset>utf8</charset>
    </encoder> 
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
        <fileNamePattern>logstash/logstash-%d{yyyy-MM-dd}.log</fileNamePattern>  
    </rollingPolicy>  
</appender>

4.将某一个logger输入到这个appender上

<logger name="xxx" additivity="false">
   <level value="INFO" />
   <appender-ref ref="LOGSTASH" />
</logger>

 

使用log4j

1.spring boot默认使用logback记录日志,所以首先要从组件spring-boot-starter-logging中剔除logback,再引入log4j,代码如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<exclusions>
<exclusion>
<artifactId>logback-classic</artifactId>
<groupId>ch.qos.logback</groupId>
</exclusion>
</exclusions>

</dependency>

2.添加logstash日志格式的支持:

<dependency>
<groupId>net.logstash.log4j</groupId>
<artifactId>jsonevent-layout</artifactId>
<version>1.7</version>
</dependency>

3.在spring boot的配置文件application.properties指定使用log4j作为日志组件

#指定log4j.properties的位置

logging.config=config/log4j.properties

4.log4j.properties中添加用来记录logstash的appender

log4j.logger.xxx=INFO,logstash

log4j.appender.logstash=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logstash.File=logstash/logstash.log
log4j.appender.logstash.Append=true
log4j.appender.logstash.Encoding=UTF-8
log4j.appender.logstash.layout=net.logstash.log4j.JSONEventLayoutV1

posted on 2017-08-01 13:25  adolfmc  阅读(787)  评论(0编辑  收藏  举报