在https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout中,它描述了如何以纳秒精度格式化日志时间戳。此外,在http://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties中,据说默认的时间戳来自System.getCurrentTimeMillis()
,如果您想要一个不同的时钟,则应该将log4j2.component.properties
中的属性log4j2.clock
设置为实现org.apache.logging.log4j.core.util.Clock
的类的完全限定类名。在https://logging.apache.org/log4j/2.x/log4j-core/apidocs/index.html中,我看到上述接口只允许毫秒精度,但它有一个子接口org.apache.logging.log4j.core.time.PreciseClock
,它允许纳秒精度。我已经实现了一个类
package my.package;
import java.time.Instant;
import org.apache.logging.log4j.core.time.MutableInstant;
import org.apache.logging.log4j.core.time.PreciseClock;
/**
* Provides the current time up to nanosecond precision, as supported by the platform.
* Note that most current platforms provide only microsecond precision.
*/
public class NanoSecondClock implements PreciseClock {
/**
* Returns the time in milliseconds since the epoch.
* @return the time in milliseconds since the epoch.
*/
public long currentTimeMillis(){return System.currentTimeMillis();}
/**
* Initializes the specified instant with time information as accurate as available on this platform.
* @param mutableInstant The container to be initialized with the accurate time information.
*/
public void init(MutableInstant mutableInstant){
Instant now=Instant.now();
mutableInstant.initFromEpochSecond(now.getEpochSecond(),now.getNano());
}
}
这个类提供毫秒和纳秒的精度,因为它必须实现接口。我已将上述属性设置为该类。现在,在我的日志中,我只看到毫秒精度的时间戳,尽管我已经测试过我的平台在Instant.now()
中支持微秒精度。
我是不是忽略了什么?
发布于 2022-10-10 09:50:22
您可以在o.a.l.l.core.util.ClockFactory#createClock()
中放置一个断点,以查看您的配置中缺少什么。简单地说,设置log4j.clock=my.package.NanoSecondClock
系统属性应该很简单。
请考虑日期时间格式化是日志事件生命周期中最耗时的操作之一。Log4j在引擎盖下使用各种技巧,使其表现得很好。在那里,缓存起着至关重要的作用。通过提高时间精度,您就没有了这样的缓存机会。我强烈建议你重新评估你在日志中对纳秒精度时间戳的需求。
https://stackoverflow.com/questions/69768131
复制相似问题