javalogbackstructured-logging

Logback structured logging format timestamp via logback.xml


I want to format the timestamp in my structured logs. Currently I defined the logback.xml like:

<configuration>
<appender name="json" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <fieldNames>
            <timestamp>timestamp</timestamp>
            <logger>[ignore]</logger>
            <version>[ignore]</version>
            <levelValue>[ignore]</levelValue>
            <stackTrace>exception</stackTrace>
        </fieldNames>
    </encoder>
</appender>

<root name="jsonLogger" level="DEBUG">
    <appender-ref ref="json"/>
</root>

</configuration>

Using <fieldNames>I am able to change the name of the timestamp field.

How can I change the pattern of the timestamp via the configuration in logback.xml?


Solution

  • If figured out that I can add <timeZone> and <timestampPattern> to the encoder to format my timestamp.

    The complete configuration then becomes:

    <configuration>
    <appender name="json" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <timeZone>UTC</timeZone>
            <timestampPattern>yyyy-MM-dd'T'HH:mm:ss.SSS</timestampPattern>
            <fieldNames>
                <timestamp>timestamp</timestamp>
                <logger>[ignore]</logger>
                <version>[ignore]</version>
                <levelValue>[ignore]</levelValue>
                <stackTrace>exception</stackTrace>
            </fieldNames>
        </encoder>
    </appender>
    
    <root name="jsonLogger" level="DEBUG">
        <appender-ref ref="json"/>
    </root>
    
    </configuration>