首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Log4j2:我如何获得具有纳秒精度的时间戳?

Log4j2:我如何获得具有纳秒精度的时间戳?
EN

Stack Overflow用户
提问于 2021-10-29 11:30:03
回答 1查看 343关注 0票数 0

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,它允许纳秒精度。我已经实现了一个类

代码语言:javascript
运行
复制
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()中支持微秒精度。

我是不是忽略了什么?

EN

Stack Overflow用户

发布于 2022-10-10 09:50:22

您可以在o.a.l.l.core.util.ClockFactory#createClock()中放置一个断点,以查看您的配置中缺少什么。简单地说,设置log4j.clock=my.package.NanoSecondClock系统属性应该很简单。

请考虑日期时间格式化是日志事件生命周期中最耗时的操作之一。Log4j在引擎盖下使用各种技巧,使其表现得很好。在那里,缓存起着至关重要的作用。通过提高时间精度,您就没有了这样的缓存机会。我强烈建议你重新评估你在日志中对纳秒精度时间戳的需求。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69768131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档