- java.lang.Object
-
- ch.qos.logback.core.spi.ContextAwareBase
-
- ch.qos.logback.core.encoder.EncoderBase<ILoggingEvent>
-
- ch.qos.logback.classic.encoder.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. EachILoggingEventis 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, theappendCustomFields(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 exceptwithFormattedMessage.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:
- JSON Lines,
RFC 8259 (The JavaScript Object Notation (JSON) Data Interchange Format),
EncoderBase
-
-
Field Summary
-
Fields inherited from class ch.qos.logback.core.encoder.EncoderBase
started
-
Fields inherited from class ch.qos.logback.core.spi.ContextAwareBase
context
-
-
Constructor Summary
Constructors Constructor Description JsonEncoder()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected voidappendArgumentArray(StringBuilder sb, ILoggingEvent event)protected voidappendCustomFields(StringBuilder sb, ILoggingEvent event)Hook allowing subclasses to append additional fields into the root JSON object.protected voidappenderMember(StringBuilder sb, String key, String value)protected voidappenderMemberWithIntValue(StringBuilder sb, String key, int value)protected voidappenderMemberWithLongValue(StringBuilder sb, String key, long value)protected voidappendKeyValuePairs(StringBuilder sb, ILoggingEvent event)protected voidappendLoggerContext(StringBuilder sb, LoggerContextVO loggerContextVO)protected voidappendMap(StringBuilder sb, String attrName, Map<String,String> map)protected voidappendMarkers(StringBuilder sb, ILoggingEvent event)protected voidappendMDC(StringBuilder sb, ILoggingEvent event)protected voidappendSTEPArray(StringBuilder sb, StackTraceElementProxy[] stepArray, int commonFrames)protected voidappendThrowableProxy(StringBuilder sb, String attributeName, IThrowableProxy itp)protected voidappendThrowableProxy(StringBuilder sb, String attributeName, IThrowableProxy itp, boolean appendValueSeparator)protected voidappendValueSeparator(StringBuilder sb, boolean... subsequentConditionals)Append a JSON value separator (a comma) to the providedStringBuilderwhen any of the supplied boolean flags indicate that a subsequent element is present.byte[]encode(ILoggingEvent event)Encode an event as bytes.byte[]footerBytes()Get footer bytes.byte[]headerBytes()Get header bytes.voidsetWithArguments(boolean withArguments)Enable or disable the inclusion of the event argument array in the encoded output.voidsetWithContext(boolean withContext)Enable or disable the inclusion of the logger context information.voidsetWithFormattedMessage(boolean withFormattedMessage)Enable or disable the inclusion of the formatted message in the encoded output.voidsetWithKVPList(boolean withKVPList)Enable or disable the inclusion of key-value pairs attached to the logging event.voidsetWithLevel(boolean withLevel)Enable or disable the inclusion of the log level in the encoded output.voidsetWithLoggerName(boolean withLoggerName)Enable or disable the inclusion of the logger name in the encoded output.voidsetWithMarkers(boolean withMarkers)Enable or disable the inclusion of markers in the encoded output.voidsetWithMDC(boolean withMDC)Enable or disable the inclusion of MDC properties in the encoded output.voidsetWithMessage(boolean withMessage)Enable or disable the inclusion of the raw message text in the encoded output.voidsetWithNanoseconds(boolean withNanoseconds)Set whether nanoseconds will be included in the timestamp output.voidsetWithSequenceNumber(boolean withSequenceNumber)Set whether the sequence number is included in each encoded event.voidsetWithThreadName(boolean withThreadName)Enable or disable the inclusion of the thread name in the encoded output.voidsetWithThrowable(boolean withThrowable)Enable or disable the inclusion of throwable information in the encoded output.voidsetWithTimestamp(boolean withTimestamp)Set whether the event timestamp is included in each encoded event.-
Methods inherited from class ch.qos.logback.core.encoder.EncoderBase
isStarted, start, stop
-
Methods inherited from class ch.qos.logback.core.spi.ContextAwareBase
addError, addError, addInfo, addInfo, addStatus, addWarn, addWarn, getContext, getDeclaredOrigin, getStatusManager, setContext
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface ch.qos.logback.core.spi.ContextAware
addError, addError, addInfo, addInfo, addStatus, addWarn, addWarn, getContext, setContext
-
-
-
-
Field Detail
-
CONTEXT_ATTR_NAME
public static final String CONTEXT_ATTR_NAME
- See Also:
- Constant Field Values
-
NAME_ATTR_NAME
public static final String NAME_ATTR_NAME
- See Also:
- Constant Field Values
-
BIRTHDATE_ATTR_NAME
public static final String BIRTHDATE_ATTR_NAME
- See Also:
- Constant Field Values
-
CONTEXT_PROPERTIES_ATTR_NAME
public static final String CONTEXT_PROPERTIES_ATTR_NAME
- See Also:
- Constant Field Values
-
TIMESTAMP_ATTR_NAME
public static final String TIMESTAMP_ATTR_NAME
- See Also:
- Constant Field Values
-
NANOSECONDS_ATTR_NAME
public static final String NANOSECONDS_ATTR_NAME
- See Also:
- Constant Field Values
-
SEQUENCE_NUMBER_ATTR_NAME
public static final String SEQUENCE_NUMBER_ATTR_NAME
- See Also:
- Constant Field Values
-
LEVEL_ATTR_NAME
public static final String LEVEL_ATTR_NAME
- See Also:
- Constant Field Values
-
MARKERS_ATTR_NAME
public static final String MARKERS_ATTR_NAME
- See Also:
- Constant Field Values
-
THREAD_NAME_ATTR_NAME
public static final String THREAD_NAME_ATTR_NAME
- See Also:
- Constant Field Values
-
MDC_ATTR_NAME
public static final String MDC_ATTR_NAME
- See Also:
- Constant Field Values
-
LOGGER_ATTR_NAME
public static final String LOGGER_ATTR_NAME
- See Also:
- Constant Field Values
-
MESSAGE_ATTR_NAME
public static final String MESSAGE_ATTR_NAME
- See Also:
- Constant Field Values
-
FORMATTED_MESSAGE_ATTR_NAME
public static final String FORMATTED_MESSAGE_ATTR_NAME
- See Also:
- Constant Field Values
-
ARGUMENT_ARRAY_ATTR_NAME
public static final String ARGUMENT_ARRAY_ATTR_NAME
- See Also:
- Constant Field Values
-
KEY_VALUE_PAIRS_ATTR_NAME
public static final String KEY_VALUE_PAIRS_ATTR_NAME
- See Also:
- Constant Field Values
-
THROWABLE_ATTR_NAME
public static final String THROWABLE_ATTR_NAME
- See Also:
- Constant Field Values
-
CAUSE_ATTR_NAME
public static final String CAUSE_ATTR_NAME
- See Also:
- Constant Field Values
-
SUPPRESSED_ATTR_NAME
public static final String SUPPRESSED_ATTR_NAME
- See Also:
- Constant Field Values
-
COMMON_FRAMES_COUNT_ATTR_NAME
public static final String COMMON_FRAMES_COUNT_ATTR_NAME
- See Also:
- Constant Field Values
-
CLASS_NAME_ATTR_NAME
public static final String CLASS_NAME_ATTR_NAME
- See Also:
- Constant Field Values
-
METHOD_NAME_ATTR_NAME
public static final String METHOD_NAME_ATTR_NAME
- See Also:
- Constant Field Values
-
STEP_ARRAY_NAME_ATTRIBUTE
public static final String STEP_ARRAY_NAME_ATTRIBUTE
- See Also:
- Constant Field Values
-
OPEN_OBJ
protected static final char OPEN_OBJ
- See Also:
- Constant Field Values
-
CLOSE_OBJ
protected static final char CLOSE_OBJ
- See Also:
- Constant Field Values
-
OPEN_ARRAY
protected static final char OPEN_ARRAY
- See Also:
- Constant Field Values
-
CLOSE_ARRAY
protected static final char CLOSE_ARRAY
- See Also:
- Constant Field Values
-
QUOTE
protected static final char QUOTE
- See Also:
- Constant Field Values
-
SP
protected static final char SP
- See Also:
- Constant Field Values
-
ENTRY_SEPARATOR
protected static final char ENTRY_SEPARATOR
- See Also:
- Constant Field Values
-
COL_SP
protected static final String COL_SP
- See Also:
- Constant Field Values
-
QUOTE_COL
protected static final String QUOTE_COL
- See Also:
- Constant Field Values
-
VALUE_SEPARATOR
protected static final char VALUE_SEPARATOR
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
JsonEncoder
public JsonEncoder()
-
-
Method Detail
-
headerBytes
public byte[] headerBytes()
Description copied from interface:EncoderGet header bytes. This method is typically called upon opening of an output stream.- Returns:
- header bytes. Null values are allowed.
-
encode
public byte[] encode(ILoggingEvent event)
Description copied from interface:EncoderEncode an event as bytes.
-
appendValueSeparator
protected void appendValueSeparator(StringBuilder sb, boolean... subsequentConditionals)
Append a JSON value separator (a comma) to the providedStringBuilderwhen any of the supplied boolean flags indicate that a subsequent element is present.Callers pass a sequence of booleans that represent whether subsequent JSON members will be written. If at least one of those booleans is
true, this method appends a single comma (',') to separate JSON fields.This method is protected so subclasses that extend the encoder can reuse or override the logic for inserting separators between generated JSON members.
- Parameters:
sb- theStringBuilderto append the separator to; must not benullsubsequentConditionals- one or more booleans indicating whether subsequent JSON elements will be written. If any value istrue, a comma is appended.
-
appendLoggerContext
protected void appendLoggerContext(StringBuilder sb, LoggerContextVO loggerContextVO)
-
appendThrowableProxy
protected void appendThrowableProxy(StringBuilder sb, String attributeName, IThrowableProxy itp)
-
appendThrowableProxy
protected void appendThrowableProxy(StringBuilder sb, String attributeName, IThrowableProxy itp, boolean appendValueSeparator)
-
appendSTEPArray
protected void appendSTEPArray(StringBuilder sb, StackTraceElementProxy[] stepArray, int commonFrames)
-
appendCustomFields
protected void appendCustomFields(StringBuilder sb, ILoggingEvent event)
Hook allowing subclasses to append additional fields into the root JSON object. Default implementation is a no-op.Subclasses may append additional top-level JSON members here. If a subclass writes additional members it should prepend them with
VALUE_SEPARATOR(a comma) if necessary to keep the JSON valid. Implementations must not close the root JSON object or write the final line separator;JsonEncoderhandles those.- Parameters:
sb- the StringBuilder that accumulates the JSON output; never nullevent- the logging event being encoded; never null
-
appenderMember
protected void appenderMember(StringBuilder sb, String key, String value)
-
appenderMemberWithIntValue
protected void appenderMemberWithIntValue(StringBuilder sb, String key, int value)
-
appenderMemberWithLongValue
protected void appenderMemberWithLongValue(StringBuilder sb, String key, long value)
-
appendKeyValuePairs
protected void appendKeyValuePairs(StringBuilder sb, ILoggingEvent event)
-
appendArgumentArray
protected void appendArgumentArray(StringBuilder sb, ILoggingEvent event)
-
appendMarkers
protected void appendMarkers(StringBuilder sb, ILoggingEvent event)
-
appendMDC
protected void appendMDC(StringBuilder sb, ILoggingEvent event)
-
footerBytes
public byte[] footerBytes()
Description copied from interface:EncoderGet footer bytes. This method is typically called prior to the closing of the stream where events are written.- Returns:
- footer bytes. Null values are allowed.
-
setWithSequenceNumber
public void setWithSequenceNumber(boolean withSequenceNumber)
Set whether the sequence number is included in each encoded event.- Parameters:
withSequenceNumber-trueto include the sequence number in the output- Since:
- 1.5.0
-
setWithTimestamp
public void setWithTimestamp(boolean withTimestamp)
Set whether the event timestamp is included in each encoded event.- Parameters:
withTimestamp-trueto include the event timestamp in the output- Since:
- 1.5.0
-
setWithNanoseconds
public void setWithNanoseconds(boolean withNanoseconds)
Set whether nanoseconds will be included in the timestamp output.- Parameters:
withNanoseconds-trueto include nanoseconds in the timestamp output- Since:
- 1.5.0
-
setWithLevel
public void setWithLevel(boolean withLevel)
Enable or disable the inclusion of the log level in the encoded output.- Parameters:
withLevel-trueto include the log level. Default istrue.
-
setWithThreadName
public void setWithThreadName(boolean withThreadName)
Enable or disable the inclusion of the thread name in the encoded output.- Parameters:
withThreadName-trueto include the thread name. Default istrue.
-
setWithLoggerName
public void setWithLoggerName(boolean withLoggerName)
Enable or disable the inclusion of the logger name in the encoded output.- Parameters:
withLoggerName-trueto include the logger name. Default istrue.
-
setWithContext
public void setWithContext(boolean withContext)
Enable or disable the inclusion of the logger context information.- Parameters:
withContext-trueto include the logger context. Default istrue.
-
setWithMarkers
public void setWithMarkers(boolean withMarkers)
Enable or disable the inclusion of markers in the encoded output.- Parameters:
withMarkers-trueto include markers. Default istrue.
-
setWithMDC
public void setWithMDC(boolean withMDC)
Enable or disable the inclusion of MDC properties in the encoded output.- Parameters:
withMDC-trueto include MDC properties. Default istrue.
-
setWithKVPList
public void setWithKVPList(boolean withKVPList)
Enable or disable the inclusion of key-value pairs attached to the logging event.- Parameters:
withKVPList-trueto include the key/value pairs list. Default istrue.
-
setWithMessage
public void setWithMessage(boolean withMessage)
Enable or disable the inclusion of the raw message text in the encoded output.- Parameters:
withMessage-trueto include the message. Default istrue.
-
setWithArguments
public void setWithArguments(boolean withArguments)
Enable or disable the inclusion of the event argument array in the encoded output.- Parameters:
withArguments-trueto include the argument array. Default istrue.
-
setWithThrowable
public void setWithThrowable(boolean withThrowable)
Enable or disable the inclusion of throwable information in the encoded output.- Parameters:
withThrowable-trueto include throwable/stacktrace information. Default istrue.
-
setWithFormattedMessage
public void setWithFormattedMessage(boolean withFormattedMessage)
Enable or disable the inclusion of the formatted message in the encoded output.- Parameters:
withFormattedMessage-trueto include the formatted message. Default isfalse.
-
-