Search code examples
logback

How can I format the date as epoch timestamp in logback?


I am using logback and I want to print an epoch timestamp instead of the date and time.

https://logback.qos.ch/manual/layouts.html#contextName references https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html where there is no way to format a date as epoch.

I can't believe this essential functionality isn't available, but I googled for a while and couldn't find it.

What I found is the same question for log4j log4j : current time in milliseconds, but what @thegeko suggests there %d{UNIX_MILLIS} doesn't work for me in logback.

Does anybody know?


Solution

  • You can use this snippet to print Unix Epoch:

    <layout class="net.logstash.logback.layout.LogstashLayout">
        <timeZone>UTC</timeZone>
        <timestampPattern>[UNIX_TIMESTAMP_AS_NUMBER]</timestampPattern>
    </layout>
    

    Reference: https://github.com/logstash/logstash-logback-encoder#customizing-timestamp