LogBack - LogStash - 在logback中添加属性并将它们发送到Logstash

时间:2016-12-22 12:07:29

标签: spring-boot logstash logback logstash-grok logstash-logback-encoder

我在SpringBoot应用程序中使用Logback和Logstash。

在logback.xml中,我有一个带有服务名称的属性,如:

<configuration>

<include resource="org/springframework/boot/logging/logback/defaults.xml" />

<include resource="org/springframework/boot/logging/logback/console-appender.xml" />

<property name="spring.application.name" calue="service"/>

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>localhost:9600</destination>
    <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>

<root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="stash" />
</root>

</configuration>

Logstash配置文件如:

input{ tcp{
        port=> 9600
        host=>logstash
    }
}

filter {
grok {
match => {
  "message" =>
  "^%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:level}\s+%{NUMBER:pid}\s+---\s+\[\s*%{USERNAME:thread}\s*\]\s+%{JAVAFILE:class}\s*:\s*%{DATA:themessage}(?:\n+(?<stacktrace>(?:.|\r|\n)+))?$"
}
}
date {
match => [ "timestamp" , "yyyy-MM-dd HH:mm:ss.SSS" ]
}
 mutate {
remove_field => ["@version"]
add_field => {
  "appid" => "%{[path]}"
}
add_field => {
  "levell" => "level"
}
add_field => {
  "mensage" => "message"
}
 }
   }
output{

 elasticsearch {
hosts => ["elasticsearch"]
index => "indice"
 }
   stdout{}
 } 

如何将logback文件中的应用程序名称属性添加为字段?

2 个答案:

答案 0 :(得分:3)

您可以按如下方式为LogstashEncoder配置自定义字段

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>192.168.99.100:4560</destination>

    <!-- encoder is required -->
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
      <customFields>{"appname":"${appName}"}</customFields>
    </encoder>
</appender>

例如,对于spring boot应用程序,您可以使用获取弹簧范围属性,如下所示

<springProperty name="appName" source="spring.application.name"/>

或以其他方式从.properties文件导入属性

<property  resource="application.properties" />

答案 1 :(得分:0)

来自logstash-logback-encoder docs:

  

默认情况下,Logback的Context(ch.qos.logback.core.Context)的每个属性(如HOSTNAME)将在LoggingEvent中显示为一个字段。可以通过在encoder / layout / appender配置中指定false来禁用它。

默认情况下,您的logback属性是本地范围,不包括在内。尝试将它们设置为scope="context"

<property name="spring.application.name" value="service" scope="context"/>