'Spring Boot Slf4j change log timestamp to use UTC timezone
Spring boot app with default logger settings and using lombok's @Slf4j
Prints logs like
{"timestamp":"2020-02-26T11:25:57.485-05:00" ..........}
Time shown 11:25 is in EST or NewYork timezone
How do we change this to log timestamp in UTC timezone?
I have tried setting
logging:
pattern:
dateformat: yyyy-MM-dd HH:mm:ss.SSS, UTC
Also setting JVM level timzone by using
@PostConstruct
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
and have also tried configuring in application.yaml logging:
pattern:
console: '%d{"yyyy/MM/dd HH:mm:ss,SSS,UTC"} [%p] [%t] %M\(%F:%L\) - %msg%n'
Solution 1:[1]
The problem that happens to you described in the slf4j docs
After checking the date format I've noticed that indeed the dateformat
logging:
pattern:
dateformat: you date format
Is not working for some reason
But if you will use the console configuration it will work
logging:
pattern:
console: '%date{"yyyy/MM/dd HH:mm:ss,SSS", UTC} [%p] [%t] %M\(%F:%L\) - %msg%n'
Notice that the apostrophes should be only on the date format and not on the timezone, because the time sone is the second parameter for the slf4j date format parser function.
As mentioned in the slf4j docs:
COMMON ERROR - Given that the comma ',' character is interpreted as the parameter separator, the pattern HH:mm:ss,SSS will be interpreted as the pattern HM:mm:ss and the timezone SSS. If you wish to include a comma in your date pattern, then simply enclose the pattern between quotes. For example, %date{"HH:mm:ss,SSS"}.
Solution 2:[2]
So the provided answer doesn't seem to work. This format works though:
%date{"yyyy-MM-dd HH:mm:ss.SSSZ"}{America/Denver}
Solution 3:[3]
Below one worked for me to Change from UTC to CDT.
%date{"yyyy-MM-dd HH:mm:ss.SSSZ","America/Chicago"}
Solution 4:[4]
Using SpringBoot 2.6.6 with (the default) logback, this worked for me:
logging:
pattern:
dateformat: "\"yyyy-MM-dd'T'HH:mm:ss,SSSXXX\", UTC"
The resulting timestamp looks like this: 2022-04-27T13:41:38,500Z
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel Taub |
Solution 2 | Tim Schimandle |
Solution 3 | |
Solution 4 | Ralf |