与大多数其他日志框架一样,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/