java - 将日志参数转换为logback中的字符串

标签 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因为这很容易忘记并且使代码的可读性较差。

最佳答案

只要没有答案,我就使用这个类:

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"

关于java - 将日志参数转换为logback中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39019410/

相关文章:

java - 没有 jcl-over-slf4j 的 Spring + Logback(slf4j) 日志记录

java - ExtJS 文件上传响应?

jboss - Logback + Wildfly 8 - 不正确的模式

java - Mapbox:如果我们想在 map 上显示一条线,是否需要LineLayer

java - Java中的变量阴影

java - Logback:记录器功能不在控制台中打印消息。

spring-boot 从 1.3.2 升级到 1.3.3 : logback issue

java - 使用 SLF4J,是否可以对错误/警告采取行动?

java - 如果[WEB-INF/lib]和[tomcat/lib]包含类似的JAR会发生什么?

Java 的 jar : How do I create a . jar 文件来自特定的文件列表并且还使用 -C 选项?