• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

logfellow/logstash-logback-encoder: Logback JSON encoder and appenders

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

logfellow/logstash-logback-encoder

开源软件地址:

https://github.com/logfellow/logstash-logback-encoder

开源编程语言:

Java 99.8%

开源软件介绍:

!! This document applies to the next version under development.

    See here for documentation on the latest released version.

Logstash Logback Encoder

Build Javadocs Maven Central Release Notes

Provides logback encoders, layouts, and appenders to log in JSON and other formats supported by Jackson.

Supports both regular LoggingEvents (logged through a Logger) and AccessEvents (logged via logback-access).

Originally written to support output in logstash's JSON format, but has evolved into a highly-configurable, general-purpose, structured logging mechanism for JSON and other Jackson dataformats. The structure of the output, and the data it contains, is fully configurable.

Contents:

Including it in your project

Maven style:

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>7.2</version>
    <!-- Use runtime scope if the project does not have any compile-time usage of logstash-logback-encoder,
         such as usage of StructuredArguments/Markers or implementations such as
         JsonProvider, AppenderListener, JsonFactoryDecorator, JsonGeneratorDecorator, etc
    <scope>runtime</scope>
    -->
</dependency>
<!-- Your project must also directly depend on either logback-classic or logback-access.  For example: -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.11</version>
    <!-- Use runtime scope if the project does not have any compile-time usage of logback,
         such as implementations of Appender, Encoder, Layout, TurboFilter, etc
    <scope>runtime</scope>
    -->
</dependency>

If you get ClassNotFoundException/NoClassDefFoundError/NoSuchMethodError at runtime, then ensure the required dependencies (and appropriate versions) as specified in the pom file from the maven repository exist on the runtime classpath. Specifically, the following need to be available on the runtime classpath:

  • jackson-databind / jackson-core / jackson-annotations >= 2.12.0
  • logback-core >= 1.2.0
  • logback-classic >= 1.2.0 (required for logging LoggingEvents)
  • logback-access >= 1.2.0 (required for logging AccessEvents)
  • slf4j-api
  • java-uuid-generator (required if the uuid provider is used)

Older versions than the ones specified in the pom file might work, but the versions in the pom file are what testing has been performed against. Support for logback versions prior to 1.2.0 was removed in logstash-logback-encoder 7.0.

If you are using logstash-logback-encoder in a project (such as spring-boot) that also declares dependencies on any of the above libraries, you might need to tell maven explicitly which versions to use to avoid conflicts. You can do so using maven's dependencyManagement feature. For example, to ensure that maven doesn't pick different versions of logback-core, logback-classic, and logback-access, add this to your project's pom.xml

<properties>
    <logback.version>1.2.6</logback.version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-access</artifactId>
            <version>${logback.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

Java Version Requirements

logstash-logback-encoder Minimum Java Version supported
>= 6.0 1.8
5.x 1.7
<= 4.x 1.6

Usage

To log using JSON format, you must configure logback to use either:

  • an appender provided by the logstash-logback-encoder library, OR
  • an appender provided by logback (or another library) with an encoder or layout provided by the logstash-logback-encoder library

The appenders, encoders, and layouts provided by the logstash-logback-encoder library are as follows:

Format Protocol Function LoggingEvent AccessEvent
Logstash JSON Syslog/UDP Appender LogstashUdpSocketAppender LogstashAccessUdpSocketAppender
Logstash JSON TCP Appender LogstashTcpSocketAppender LogstashAccessTcpSocketAppender
any any Appender LoggingEventAsyncDisruptorAppender AccessEventAsyncDisruptorAppender
Logstash JSON any Encoder LogstashEncoder LogstashAccessEncoder
Logstash JSON any Layout LogstashLayout LogstashAccessLayout
General JSON any Encoder LoggingEventCompositeJsonEncoder AccessEventCompositeJsonEncoder
General JSON any Layout LoggingEventCompositeJsonLayout AccessEventCompositeJsonLayout

These encoders/layouts can generally be used by any logback appender (such as RollingFileAppender).

The general composite JSON encoders/layouts can be used to output any JSON format/data by configuring them with various JSON providers. The Logstash encoders/layouts are really just extensions of the general composite JSON encoders/layouts with a pre-defined set of providers.

The logstash encoders/layouts are easier to configure if you want to use the standard logstash version 1 output format. Use the composite encoders/layouts if you want to heavily customize the output, or if you need to use logstash version 0 output.

The *AsyncDisruptorAppender appenders are similar to logback's AsyncAppender, except that a LMAX Disruptor RingBuffer is used as the queuing mechanism, as opposed to a BlockingQueue. These async appenders can delegate to any other underlying logback appender.

UDP Appender

To output JSON for LoggingEvents to a syslog/UDP channel, use the LogstashUdpSocketAppender with a LogstashLayout or LoggingEventCompositeJsonLayout in your logback.xml, like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
        <host>MyAwesomeSyslogServer</host>
        <!-- port is optional (default value shown) -->
        <port>514</port>
        <!-- layout is required -->
        <layout class="net.logstash.logback.layout.LogstashLayout"/>
    </appender>
    
    <root level="all">
        <appender-ref ref="stash" />
  </root>
</configuration>

You can further customize the JSON output by customizing the layout as described in later sections.

For example, to configure global custom fields, you can specify

<appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
    <host>MyAwesomeSyslogServer</host>
    <!-- port is optional (default value shown) -->
    <port>514</port>
    <layout class="net.logstash.logback.layout.LogstashLayout">
        <customFields>{"appname":"myWebservice"}</customFields>
    </layout>
</appender>

To output JSON for AccessEvents over UDP, use a LogstashAccessUdpSocketAppender with a LogstashAccessLayout or AccessEventCompositeJsonLayout in your logback-access.xml, like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stash" class="net.logstash.logback.appender.LogstashAccessUdpSocketAppender">
        <host>MyAwesomeSyslogServer</host>
        <!-- port is optional (default value shown) -->
        <port>514</port>

        <layout class="net.logstash.logback.layout.LogstashAccessLayout">
            <customFields>{"appname":"myWebservice"}</customFields>
        </layout>
    </appender>

    <appender-ref ref="stash" />
</configuration>

To receive syslog/UDP input in logstash, configure a syslog or udp input with the json codec in logstash's configuration like this:

input {
    syslog {
        codec => "json"
    }
}

TCP Appenders

To output JSON for LoggingEvents over TCP, use a LogstashTcpSocketAppender with a LogstashEncoder or LoggingEventCompositeJsonEncoder in your logback.xml, like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>127.0.0.1:4560</destination>

        <!-- encoder is required -->
        <encoder class="net.logstash.logback.encoder.LogstashEncoder" />
    </appender>

    <root level="DEBUG">
        <appender-ref ref="stash" />
    </root>
</configuration>

To output JSON for AccessEvents over TCP, use a LogstashAccessTcpSocketAppender with a LogstashAccessEncoder or AccessEventCompositeJsonEncoder in your logback-access.xml, like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stash" class="net.logstash.logback.appender.LogstashAccessTcpSocketAppender">
        <destination>127.0.0.1:4560</destination>

        <!-- encoder is required -->
        <encoder class="net.logstash.logback.encoder.LogstashAccessEncoder" />
    </appender>

    <appender-ref ref="stash" />
</configuration>

The TCP appenders use an encoder, rather than a layout as the UDP appenders . You can use a Logstash*Encoder, *EventCompositeJsonEncoder, or any other logback encoder. All of the output formatting options are configured at the encoder level.

Internally, the TCP appenders are asynchronous (using the LMAX Disruptor RingBuffer). All the encoding and TCP communication is delegated to a single writer thread. There is no need to wrap the TCP appenders with another asynchronous appender (such as AsyncAppender or LoggingEventAsyncDisruptorAppender).

All the configuration parameters (except for sub-appender) of the async appenders are valid for TCP appenders. For example, waitStrategyType and ringBufferSize.

The TCP appenders will never block the logging thread. If the RingBuffer is full (e.g. due to slow network, etc), then events will be dropped.

The TCP appenders will automatically reconnect if the connection breaks. However, events may be lost before Java's socket realizes the connection has broken.

To receive TCP input in logstash, configure a tcp input with the json_lines codec in logstash's configuration like this:

input {
    tcp {
        port => 4560
            codec => json_lines
    }
}

In order to guarantee that logged messages have had a chance to be processed by the TCP appender, you'll need to cleanly shut down logback when your application exits.

Keep-Alive

If events occur infrequently, and the connection breaks consistently due to a server-side idle timeout, then you can enable keep alive functionality by configuring a keepAliveDuration like this:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...
    <keepAliveDuration>5 minutes</keepAliveDuration>
</appender>

This setting accepts a Logback Duration value - see the section dedicated to Duration Property for more information about the valid values.

When the keepAliveDuration is set, then a keep alive message will be sent if an event has not occurred for the length of the duration. The keep alive message defaults to unix line ending (\n), but can be changed by setting the keepAliveMessage property to the desired value. The following values have special meaning:

  • <empty string>: no keep alive
  • SYSTEM: system's line separator
  • UNIX: unix line ending (\n)
  • WINDOWS: windows line ending (\r\n)

Any other value will be used as-is.

The keep alive message is encoded in UTF-8 by default. This can be changed by setting the keepAliveCharset property to the name of the desired charset.

Multiple Destinations

The TCP appenders can be configured to try to connect to one of several destinations like this:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>destination1.domain.com:4560</destination>
    <destination>destination2.domain.com:4560</destination>
    <destination>destination3.domain.com:4560</destination>

    ...
</appender>

or this:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>
        destination1.domain.com:4560,
        destination2.domain.com:4560,
        destination3.domain.com:4560
    </destination>

    ...
</appender>

The appender uses a connectionStrategy to determine:

  • the order in which destination connections are attempted, and
  • when an established connection should be reestablished (to the next destination selected by the connection strategy).

Logs are only sent to one destination at a time (i.e. not all destinations). By default, the appender will stay connected to the connected destination until it breaks, or until the application is shut down. Some connection strategies can force a reconnect (see below). If a connection breaks, then the appender will attempt to connect to the next destination selected by the connection strategy.

The available connection strategies are as follows:

Strategy Description
preferPrimary (default) The first destination is considered the primary destination. Each additional destination is considered a secondary destination. This strategy prefers the primary destination, unless it is down. The appender will attempt to connect to each destination in the order in which they are configured. If a connection attempt fails, thes the appender will attempt to connect to the next destination. If a connection succeeds, and then closes before the minConnectionTimeBeforePrimary has elapsed, then the appender will attempt to connect to the next destination. If a connection succeeds, and then closes after the minConnectionTimeBeforePrimary has elapsed, then the appender will attempt to connect to the destinations in the order in which they are configured, starting at the first/primary destination.

The secondaryConnectionTTL can be set to gracefully close connections to secondary destinations after a specific duration. This will force the the appender to reattempt to connect to the destinations in order again. The secondaryConnectionTTL value does not affect connections to the primary destination.

The minConnectionTimeBeforePrimary (10 seconds by default) specifies the minimum amount of time that a sucessfully established connection must remain open before the next connection attempt will try the primary. i.e. If a connection stays open less than this amount of time, then the next connection attempt will attempt the next destination (instead of the primary). This is used to prevent a connection storm to the primary in the case the primary accepts a connection, and then immediately closes it.

Example:
  <appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
      <destination>destination1.domain.com:4560</destination>
      <destination>destination2.domain.com:4560</destination>
      <destination>destination3.domain.com:4560</destination>
      <connectionStrategy>
          <preferPrimary>
              <secondaryConnectionTTL>5 minutes</secondaryConnectionTTL>
          </preferPrimary>
      </connectionStrategy>
  </appender>
roundRobin This strategy attempts connections to the destination in round robin order. If a connection fails, the next destination is attempted.

The connectionTTL can be set to gracefully close connections after a specific duration. This will force the the appender to reattempt to connect to the next destination.

Example:
  <appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
      <destination>destination1.domain.com:4560</destination>
      <destination>destination2.domain.com:4560</destination>
      <destination>destination3.domain.com:4560</destination>
      <connectionStrategy>
          <roundRobin>
              <connectionTTL>5 minutes</connectionTTL>
          </roundRobin>
      </connectionStrategy>
  </appender>
random This strategy attempts connections to the destination in a random order. If a connection fails, the next random destination is attempted.

The connectionTTL can be set to gracefully close connections after a specific duration. This will force the the appender to reattempt to connect to the next random destination.

Example:
  <appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
      <destination>destination1.domain.com:4560</destination>
      <destination>destination2.domain.com:4560</destination>
      <destination>destination3.domain.com:4560</destination>
      <connectionStrategy>
          <random>
              <connectionTTL>5 minutes</connectionTTL>
          </random>
      </connectionStrategy>
  </appender>

You can also use your own custom connection strategy by implementing the DestinationConnectionStrategy interface, and configuring the appender to use it like this:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>destination1.domain.com:4560</destination>
    <destination>destination2.domain.com:4560</destination>
    <destination>destination3.domain.com:4560</destination>
    <connectionStrategy class="your.package.YourDestinationConnectionStrategy">
    </connectionStrategy>
</appender>

Reconnection Delay

By default, the TCP appender will wait 30 seconds between connection attempts to a single destination. The time between connection attempts to each destination is tracked separately.

This amount of time to delay can be changed by setting the reconnectionDelay field.

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...
    <reconnectionDelay>1 second</reconnectionDelay>
</appender>

This setting accepts a Logback Duration value - see the section dedicated to Duration Property for more information about the valid values.

Connection Timeout

By default, a connection timeout of 5 seconds is used when connecting to a remote destination. You can adjust this by setting the appender's connectionTimeout configuration property to the desired value.

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...
    <connectionTimeout>5 seconds</connectionTimeout>
</appender>

A value of 0 means "don't use a timeout and wait indefinitely" which often really means "use OS defaults".

This setting accepts a Logback Duration value - see the section dedicated to Duration Property for more information about the valid values.

Write Buffer Size

By default, a buffer size of 8192 is used to buffer socket output stream writes. You can adjust this by setting the appender's writeBufferSize.

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...
    <writeBufferSize>16384</writeBufferSize>
</appender>

Buffering can be disabled by setting the writeBufferSize to 0. Consider disabling the write buffer if you are concerned about losing data from the buffer for flaky connections. Disabling the buffer can potentially slow down the writer thread due to increased system calls, but in some environments, this does not seem to affect overall performance. See this discussion.

Write Timeouts

If a destination stops reading from its socket input, but does not close the connection, then writes from the TCP appender will eventually backup, causing the ring buffer to backup, causing events to be dropped.

To detect this situation, you can enable a write timeout, so that "stuck" writes will eventually timeout, at which point the connection will be re-established. When the write buffer is enabled, any buffered data will be lost when the connection is reestablished.

By default there is no write timeout. To enable a write timeout, do the following:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...
    <writeTimeout>1 minute</writeTimeout>
</appender>

Note that since the blocking java socket output stream used to send events does not have a concept of a write timeout, write timeouts are detected using a task scheduled periodically with the same frequency as the write timeout. For example, if the write timeout is set to 30 seconds, then a task will execute every 30 seconds to see if 30 seconds has elapsed since the start of the current write operation. Therefore, it is recommended to use longer write timeouts (e.g. > 30s, or minutes), rather than short write timeouts, so that this task does not execute too frequently. Also, this approach means that it could take up to two times the write timeout before a write timeout is detected.

The write timeout must be >0. A timeout of zero is interpreted as an infinite timeout which effecively means "no write timeout".

This setting accepts a Logback Duration value - see the section dedicated to Duration Property for more information about the valid values.

SSL

To use SSL, add an <ssl> sub-element within the <appender> element for the LogstashTcpSocketAppender or LogstashAccessTcpSocketAppender.

See the logback manual for how to configure SSL. SSL for the Logstash*TcpSocketAppenders are configured the same way as logback's SSLSocketAppender.

For example, to enable SSL using the JVM's default keystore/truststore, do the following:

<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    ...

    <!-- Enable SSL using the JVM's default keystore/truststore -->
    <ssl/>
</appender>

To use a different truststore, do the following:


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap