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