Class JsonEncoder

All Implemented Interfaces:
Encoder<ILoggingEvent>, ContextAware, LifeCycle

public class JsonEncoder extends EncoderBase<ILoggingEvent>
JSON encoder that produces one JSON object per line in JSON Lines format, suitable for structured logging. Each ILoggingEvent is encoded into a JSON object containing fields such as timestamp, level, message, and optional elements like MDC properties, markers, and stack traces.

This encoder supports extensive configuration through boolean flags to include or exclude specific fields in the output, allowing customization for different logging needs. For example, you can enable/disable sequence numbers, nanoseconds, thread names, logger context, markers, MDC, key-value pairs, arguments, and throwable information.

The encoder is designed for extensibility: subclasses can override protected methods (e.g., appendLoggerContext(java.lang.StringBuilder, ch.qos.logback.classic.spi.LoggerContextVO), appendThrowableProxy(java.lang.StringBuilder, java.lang.String, ch.qos.logback.classic.spi.IThrowableProxy), appendMarkers(java.lang.StringBuilder, ch.qos.logback.classic.spi.ILoggingEvent)) to customize how specific parts of the JSON are generated. Additionally, the appendCustomFields(java.lang.StringBuilder, ch.qos.logback.classic.spi.ILoggingEvent) hook allows appending custom top-level fields to the JSON object.

Configuration

Use the setter methods (e.g., setWithSequenceNumber(boolean), setWithTimestamp(boolean)) to control which fields are included. By default, most fields are enabled except withFormattedMessage.

Example Usage


 <appender name="JSON" class="ch.qos.logback.core.ConsoleAppender">
   <encoder class="ch.qos.logback.classic.encoder.JsonEncoder">
     <withSequenceNumber>false</withSequenceNumber>
     <withNanoseconds>false</withNanoseconds>
     <withThreadName>false</withThreadName>
   </encoder>
 </appender>
 

This produces output similar to the following (on a single line):

{"timestamp":1640995200000,"level":"INFO","loggerName":"com.example.MyClass","context":{"name":"default","birthdate":1640995200000,"properties":{}},"message":"Hello World"}
Since:
1.3.8/1.4.8
Author:
Ceki Gülcü
See Also: