log4j : current time in milliseconds

2019-01-27 14:24发布

问题:

In log4j.properties I can set PatternLayout e.g. ("[%p] %c - %m - %d %n")

Is there any symbol (%something) which returns current time in milliseconds?

回答1:

There is no Log4J symbol that does exactly what you want.

%d returns the current date with a given pattern, defined by a SimpleDateFormat (the pattern you put between the brackets), but doesn't give you the time in millis.

%r gives the number of milliseconds since the start of execution.

One possible way of achieving what you want is to extend the behaviour of Log4j, it's quite a bit more complex, but if it's absolutely necessary... here you go:

Customize log4j (edit: no longer online?)
Customize log4j (edit: 2018 alternative)

Edit: Keep in mind that, from your comment, if you need to figure out time differences between executions in different machines, you have to make sure the clocks of the machines are synchronized, or it'll be leading you to wrong conclusions.



回答2:

You can try this one.

log4j.appender.appender_name.layout=org.apache.log4j.PatternLayout
log4j.appender.appender_name.layout.ConversionPattern=%d %p [%c] - %m%n

Date params %d. For example : %d{HH:mm:ss,SSS}.

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html



回答3:

Try this,

   %d{dd MMM yyyy HH:mm:ss,SSS}


回答4:

You should be able to use %d{UNIX_MILLIS} From the manual:

%d{UNIX} outputs the UNIX time in seconds. %d{UNIX_MILLIS} outputs the UNIX time in milliseconds. The UNIX time is the difference, in seconds for UNIX and in milliseconds for UNIX_MILLIS, between the current time and midnight, January 1, 1970 UTC. While the time unit is milliseconds, the granularity depends on the operating system (Windows). This is an efficient way to output the event time because only a conversion from long to String takes place, there is no Date formatting involved.



标签: java log4j