user2772501
user2772501

Reputation: 71

log4j: timezone formatting

I would like to format the timezone information in log4j messages in the format +hh:mm such that a complete timestamp looks like this:

2013-09-05T09:32:10.703+02:00

I know the date format specifier Z, but then the output format is +hhmm and not +hh:mm. So the colon is missing:

2013-09-10T15:55:34.123+0200

Is there any way to get what I want?

Upvotes: 7

Views: 11380

Answers (3)

Ramya Musunuru
Ramya Musunuru

Reputation: 471

XXXIn pattern layout you can define time as follows specify timezone you want under {UTC}

<PatternLayout pattern="%d{ISO8601}{UTC}Z" />

Will output the following

  2024-09-25T11:38:00,901Z

or specify pattern as follows. You can edit whatever in the {} after %d to ur desired format

 <PatternLayout pattern="%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}"/>

or

 <PatternLayout pattern="%d{yyyy-MM-dd'T'HH--mm:ss.SSS'Z'}"/>

or here XXX uses UTC time that you want

<PatternLayout pattern="%d{yyyy-MM-dd'T'HH:mm:ss,SSSXXX}"/>

     will output 

    2024-09-25T13:44:12.275+02:00

Upvotes: 0

Ali
Ali

Reputation: 1590

I am using PatternLayout with logback-classic-1.2.3.jar and below date pattern gives me Sydney timezone, you need to update according to GMT

"timestamp":"%d{yyyy-MM-dd HH:mm:ss, GMT+10}"

Upvotes: 0

Paul Vargas
Paul Vargas

Reputation: 42010

Uses the following pattern:

yyyy-MM-dd'T'HH:mm:ss.SSSXXX

In the javadoc of java.text.SimpleDateFormat, you can read that (for the X letter):

ISO 8601 Time zone: The number of pattern letters designates the format for both formatting and parsing as follows:

ISO8601TimeZone:
        OneLetterISO8601TimeZone
        TwoLetterISO8601TimeZone
        ThreeLetterISO8601TimeZone
OneLetterISO8601TimeZone:
        Sign TwoDigitHours
        Z
TwoLetterISO8601TimeZone:
        Sign TwoDigitHours Minutes
        Z
ThreeLetterISO8601TimeZone:
        Sign TwoDigitHours : Minutes
        Z

e.g.

X       -08; 
XX      -0800; 
XXX     -08:00

If your configuration file is the log4j.xml, can be as follows:

<!-- console -->
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="TRACE" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="conversionPattern"
            value="%d{yyyy-MM-dd'T'hh:mm:ss.SSSXXX} %-5p (%c.java:%L).%M - %m%n" />
    </layout>
</appender>

And if you have a Java class with:

import org.apache.log4j.Logger;

public class Main {
    private static final Logger LOGGER = Logger.getLogger(Main.class);

    public static void main(String[] args) {
        LOGGER.info("Test");
    }
}

The output is as follows:

2013-09-12T08:08:18.532-05:00 INFO  (Main.java:8).main - Test

Upvotes: 15

Related Questions