0

I'm trying to change the order of the json properties in my logback file. I want to have the log level after my timestamp so it is easy to see what kind of log it is.

My current logback.xml:

<configuration scan="true" scanPeriod="30 seconds">

<appender name="json" class="ch.qos.logback.core.ConsoleAppender">
    <target>System.out</target>
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <timestampPattern>HH:mm:ss.SSS</timestampPattern>
        <fieldNames>
            <timestamp>ts</timestamp>
            <level>level</level>
            <message>msg</message>
            <thread>[ignore]</thread>
            <levelValue>[ignore]</levelValue>
            <logger>logger</logger>
            <version>[ignore]</version>
        </fieldNames>
    </encoder>
</appender>


<root level="info">
    <appender-ref ref="json"/>
</root>

Example output:

{"ts":"09:13:53.736","msg":"Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]","logger":"org.springframework.test.context.support.DefaultTestContextBootstrapper","level":"INFO"}
Michiel
  • 103
  • 1
  • 11

1 Answers1

0

To specify an explicit field order, you can switch from net.logstash.logback.encoder.LogstashEncoder to net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder, and add the providers in the order in which you want them to appear in the output.

(Note that net.logstash.logback.encoder.LogstashEncoder is just an extension of net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder with a preconfigured set of providers in a specific order.)

<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    <providers>
        <timestamp>
            <fieldName>ts</fieldName>
        </timestamp>
        <logLevel/>
        <message>
            <fieldName>msg</fieldName>
        </message>

        <!-- add more providers here for the other fields you want -->

    </providers>
</encoder>

See the logstash-logback-encoder documentation for more information on how to use the LoggingEventCompositeJsonEncoder and what other providers are available.

Phil Clay
  • 4,028
  • 17
  • 22