Make Logback include the "T" between date and time in its "%date" format for strict ISO 8601 compliance

Basil Bourque picture Basil Bourque · Apr 16, 2014 · Viewed 21.8k times · Source

By default, the Logback encoder uses a date format similar to the ISO 8601 standard. But it lacks the "T" in the middle between the date and time portions. The T makes for easier parsing, and is required by the standard (unless private parties agree otherwise).

Is there some trick to get Logback to include the T?

This…

2006-10-20T14:06:49,812

instead of this…

2006-10-20 14:06:49,812

I suppose I could re-create the entire format while adding a "T", but I wonder if there is some simpler way.

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Apr 16, 2014

Bug Report

There's a bug report about this on Logback's JIRA page. There hasn't been much development since 24/Feb/10 3:57 PM. I've just voted to attract attention. You should too.

I would provide my own date format that matches ISO 8601's.

Insert "T"

This should do the trick:

<pattern>%d{"yyyy-MM-dd'T'HH:mm:ss,SSS"} [%thread] %-5level %logger{35} - %msg %n
</pattern>

The "" are needed to make the , work as described in the documentation.

That <pattern> element belongs in your Logback configuration setting. Here is an example logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <!-- Strangely, Logback lacks a built-in formatter for ISO 8601. So, roll our own.  -->
            <Pattern>%date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </layout>
    </appender>

    <logger name="com.example" level="TRACE"/>


    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Time Zone

To be more fully ISO 8601 compliant, and for more helpful logging, you should include a time zone.

EDIT (Michael-O, 2014-06-15): That is not true, timezone is absolute optional.

To include a time zone, pass a second argument (see doc) to the %date. Pass the proper name of a time zone. Avoid the three or four letter time zone codes such as "EST" as they are neither unique nor standardized. For example, pass Australia/Perth. Generally for logging we want UTC (GMT) time, meaning without any offset. In that case, pass UTC.

You can display the time zone offset as number of hours and minutes as part of the date-time in the log. Append an X to display the time zone offset as part of the date time value.

This…

%date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC}

…produces…

2014-04-16T09:59:24,009Z

The XXX works in Java 7 and 8. In earlier versions of Java, you may be able to use a Z in the format definition to generate an offset number that lacks a colon.