Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j ConversionPattern timestamp with microseconds

I want to add microseconds in the timestamp of each entry of my log files generated with log4j, is it possible ?

I have searched in the official documentation but there are no mention of unit below the milliseconds.

Now i have a conversion pattern like the following :

%d{dd/MM/yyyy HH\:mm\:ss,SSS} %-5p [%t] - %m%n

in the date conversion pattern(%d) i want to add microseconds after the milliseconds value(SSS), is there a way to do it ?

like image 802
aleroot Avatar asked Dec 04 '11 15:12

aleroot


3 Answers

Starting from Java 9 and log4j 2.11.0, it is possible to get the timestamp even with nanoseconds.

Here are the special predefined patterns allowing to get a date time or a time with microseconds or nanoseconds:

  • Pattern: %d{ABSOLUTE_MICROS} Example of output: 14:34:02,123456
  • Pattern: %d{ABSOLUTE_NANOS} Example of output: 14:34:02,123456789
  • Pattern: %d{DEFAULT_MICROS} Example of output: 2012-11-02 14:34:02,123456
  • Pattern: %d{DEFAULT_NANOS} Example of output: 2012-11-02 14:34:02,123456789

If you need a more specific pattern use the "nano-of-second" pattern letter n instead of the "fraction-of-second" pattern letter S for example %d{dd MMM yyyy HH:mm:ss,nnnn} to %d{dd MMM yyyy HH:mm:ss,nnnnnnnnn} will give 02 Nov 2012 14:34:02,1234 to 02 Nov 2012 14:34:02,123456789.

In your case, as you need milliseconds and microseconds, your pattern could be something like %d{dd/MM/yyyy HH:mm:ss,nnnnnn}

Log4j 2.11 adds limited support for timestamps more precise than milliseconds when running on Java 9.

For more details please refer to https://logging.apache.org/log4j/2.x/manual/layouts.html

like image 144
Nicolas Filotto Avatar answered Oct 16 '22 07:10

Nicolas Filotto


If you want to display micro-seconds, you need to add this yourself. This could be done with a custom Formatter (instead of PatternFormatter)

like image 38
Peter Lawrey Avatar answered Oct 16 '22 09:10

Peter Lawrey


it is based on SimpleDateFormat and that does not support sub-millisecond formats, so microseconds can not be reported.

like image 31
aishwarya Avatar answered Oct 16 '22 09:10

aishwarya