在logback中将日志参数转换为字符串

时间:2016-08-18 13:24:10

标签: java logback

与大多数其他日志记录框架一样,logback在日志语句中使用带有对象参数的字符串,因此只有在实际需要生成/打印时才能将它们转换为日志消息:

// Calls String.valueOf(morningOrDayOrEvening) and String.valueOf(visitor)
LOG.info("Good {}, {}", morningOrDayOrEvening, visitor);

现在 我想记录java.time.Instant s作为日志消息的一部分。我不想使用字符串表示形式,而是希望它们与自定义DateTimeFormatter一致。这是一个例子:

Instant nextExecutionTime = Instant.now().plusSeconds(60);
LOG.info("Next execution at {}", nextExecutionTime);

// Actual output: Next execution at 2016-08-18T13:14:32.895Z
// Wanted output: Next execution at 2016-08-18 15:14:32.895

(我使用PatternLayout,其中%msg包含日志消息)

我不想像建议here那样为瞬间创建包装器对象,因为这很容易忘记并使代码的可读性降低。

1 个答案:

答案 0 :(得分:0)

只要没有答案,我就会使用这个课程:

public class Times {

    /** Standard date time formatter */
    private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_DATE)
            .appendLiteral(' ')
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .toFormatter()
            .withChronology(IsoChronology.INSTANCE)
            .withZone(ZoneId.systemDefault());

    /**
     * Returns a wrapper that holds a {@link Temporal} used for the {@link 
     * Object#toString()} implementation. The string representation is
     * evaluated lazily and thus good for log statements.
     * @param temporal time to format
     * @return an object with a specific {@link Object#toString()} impl
     */
    public static Object format(Temporal temporal) {
        return new Object() {
            @Override
            public String toString() {
                return FORMATTER.format(temporal);
            }
        };
    }
}

示例日志声明:

LOG.info("next execution at {}", Times.format(nextExecutionInstant));
// Prints "next execution at 2016-08-18 15:14:32.895"

这实际上很多比急切地格式化瞬间更快。我实现了类似的持续时间,所以它们看起来像这样:

LOG.info("execution took {}", Times.format(executionTime));
// Prints "execution took 2m 12s"