Search code examples
spring-bootlogstashspring-logbacklogstash-logback-encoder

Logstash StructuredArguments kv is printing ZonedDateTime variable in Timestamp format


I am using the logstash KV method for logging. In that I have a key as string and value as a object. In logs the Object is printed as JSON which is correct. But some of the variable in the JSON object which are originally ZonedDateTime are printing in logs as timestamps.

For example one of the variable is printing in log as:

"createEventDateTime":1540849347.000000000  --> actual

"createEventDateTime":"2018-10-29T21:42:27Z"  --> Expected

Solution

  • By default, Jackson writes ZonedDateTime field values as a numeric value.

    To configure Jackson to write them as an ISO-8601 compatible string, disable the WRITE_DATES_AS_TIMESTAMPS serialization feature via a JsonFactoryDecorator...

    import com.fasterxml.jackson.core.JsonFactory;
    import com.fasterxml.jackson.databind.MappingJsonFactory;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import net.logstash.logback.decorate.JsonFactoryDecorator;
    
    public class TimestampJsonFactoryDecorator implements JsonFactoryDecorator {
    
        public JsonFactory decorate(JsonFactory factory) {
            ((MappingJsonFactory) factory).getCodec()
                    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            return factory;
        }
    }
    

    Then configure the encoder to use that decorator...

        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <jsonFactoryDecorator class="your.TimestampJsonFactoryDecorator"/>
        </encoder>
    
    

    See also Customizing JSON Factory and Generator