首页 > 解决方案 > Log4j2:如何获得实际上具有纳秒精度的时间戳?

问题描述

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.clock的属性。查看https://logging.apache.org/log4j/2.x/log4j-core/apidocs/index.html,我看到所述接口只允许毫秒精度,但它有一个允许纳秒精度的子接口. 我已经实现了一个类log4j2.component.propertiesorg.apache.logging.log4j.core.util.Clockorg.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()

我忽略了什么吗?

标签: timestamplog4j2

解决方案


推荐阅读