1. 程式人生 > >springboot 傳送logback日誌到elk

springboot 傳送logback日誌到elk

1.     引入依賴

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

2.     日誌配置

在logback.xml檔案新增如下配置:

<appender name="LOGSTASH"
       class="net.logstash.logback.appender.LogstashTcpSocketAppender">
   <destination>xx.xx.xx.xx:5044</destination>
   <!-- encoder必須配置,有多種可選 -->
   <encoder charset="UTF-8"
          class="net.logstash.logback.encoder.LogstashEncoder" >
      <!-- "logName":"comba-community" 的作用是指定建立索引的名字時用,並且在生成的文件中會多了這個欄位  -->
      <customFields>{"logName":"comba-community"}</customFields>
   </encoder>
   <filter class="ch.qos.logback.classic.filter.LevelFilter">
      <level>INFO</level>
   </filter>
</appender>
<!-- additivity 避免執行2次 -->
<logger name="com.comba.controller" level="INFO" additivity="false">
   <appender-ref ref="STDOUT" />
   <appender-ref ref="INFO_FILE" />
   <appender-ref ref="ERROR_FILE" />
   <appender-ref ref="DEBUG_FILE" />
   <appender-ref ref="LOGSTASH" />
</logger>

<root level="${root.level}">
   <appender-ref ref="STDOUT" />
   <appender-ref ref="INFO_FILE" />
   <appender-ref ref="ERROR_FILE" />
   <appender-ref ref="DEBUG_FILE" />
   <appender-ref ref="LOGSTASH" />
</root>

有多個logstash IP新增如下配置:

<connectionStrategy>
<roundRobin>
<connectionTTL>5minutes</connectionTTL>
</roundRobin>
</connectionStrategy>

這個配置是向logstash輸出日誌如果有多個logstash IP或埠可以輪詢負載各埠

3.     Logstash配置

input {
    tcp {
        port => 5044
        mode => "server"
        tags => ["tags"]
        codec => json_lines
    }
}

output {
  elasticsearch {
    hosts => "192.168.2.210:9200"
    index => "%{[logName]}-%{+YYYY.MM.dd}"
    user => "elastic"
    password => "changeme"
  }
#控制檯輸出日誌
  #stdout {codec => rubydebug }
}

伺服器logstash控制輸出的日誌:

4.     參考連結