首页 > 解决方案 > 如何更改 Google 的 Flogger(Java 的流畅日志记录 API)的日期格式?

问题描述

我正在尝试使用@Flogger 注释类时应该添加以下内容的Lombok @Flogger 功能。

private static final com.google.common.flogger.FluentLogger log = com.google.common.flogger.FluentLogger.forEnclosingClass();

请参阅有关它的小文档。https://projectlombok.org/features/log

我将以下日志添加到方法中:

log.atInfo().log("This is my info message");

我在控制台中看到的输出是:

Mar 21, 2019 7:35:05 PM net.domain.Class myMethod
INFO: This is my info message

我更喜欢 24 小时时间格式的“YYYY-MM-DD HH:MM:SS.mmm”。有没有办法配置这个?我不必使用 Lombok 注释,它看起来更简单。

另外,我找不到这篇文章的鞭打标签。

标签: javalogginglombokjava.util.logging

解决方案


从输出看来,flogger正在使用JUL 的SimpleFormatter。通过设置系统属性或在 logging.properties 中定义键来控制格式。格式化程序参数在SimpleFormatter::format方法中描述。请记住,文档中的参数相差 1,因此 date 参数实际上是%1.

日期格式的语法在java.util.Formatter 中描述。

这是示例测试程序,可用于确保您的模式在运行时应用时正确编译。一种应该起作用的模式是:%1$tF %1$tT.%1$tL %2$s%n%4$s: %5$s%6$s%n.

import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;

public class Main {
    public static void main(String[] args) throws Exception {
        final String format = "%1$tF %1$tT.%1$tL %2$s%n%4$s: %5$s%6$s%n";
        final String key = "java.util.logging.SimpleFormatter.format";
        test(format);
        test(System.getProperty(key, format));
        test(LogManager.getLogManager().getProperty(key));
    }

    private static void test(String format) {
        if (format != null) {
            LogRecord record = new LogRecord(Level.INFO, "");
            System.out.println(String.format(format,
                             new java.util.Date(record.getMillis()),
                             record.getSourceClassName(),
                             record.getLoggerName(),
                             record.getLevel().getLocalizedName(),
                             record.getMessage(),
                             String.valueOf(record.getThrown())));
        } else {
            System.out.println("null format");
        }
    }
}

哪个打印:

2019-03-21 21:51:08.604 null
INFO: null

推荐阅读