log4j ConversionPattern timestamp with microseconds

☆樱花仙子☆ 提交于 2019-12-18 16:11:36

问题


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 ?


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/8376488/log4j-conversionpattern-timestamp-with-microseconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!