kotlin - Kotlin 中的字符串模板和日志框架的占位符有什么区别?

标签 kotlin logging stringtemplate

现在,我正在尝试用 Kotlin 重写我的 Java 应用程序。然后,我遇到了日志语句,比如

log.info("do the print thing for {}", arg);

所以我有两种方法可以在 Kotlin 中执行日志操作,例如 log.info("do the print thing for {}", arg)log.info("do the为 $arg") 打印内容。第一种是委托(delegate)格式给 Slf4j 或 Log4j 等框架;第二种是使用 Kotlin 字符串模板。

那么有什么区别,哪个性能更好呢?

最佳答案

一般来说,这两种方式会产生相同的日志,除非日志库在格式化消息时也配置了本地化消息和参数,而 Kotlin 的字符串插值根本不会这样做。

当您关闭日志记录(在特定级别)时,关键区别在于性能。作为SLF4J's FAQ说:

There exists a very convenient alternative based on message formats. Assuming entry is an object, you can write:

Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

After evaluating whether to log or not, and only if the decision is affirmative, will the logger implementation format the message and replace the '{}' pair with the string value of entry. In other words, this form does not incur the cost of parameter construction in case the log statement is disabled.

The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);

基本上,如果禁用日志记录,如果您使用参数化日志记录,则不会构造消息。但是,如果您使用字符串插值,将始终构建消息。

请注意,Kotlin 的字符串插值编译成类似于 Java 中的一系列字符串连接 (+) 编译成的东西(尽管这在未来可能会改变)。

"foo $bar baz"

翻译成:

StringBuilder().append("foo ").append(bar).append(" baz").toString()

另请参阅:Unable to understand why to use parameterized logging

关于kotlin - Kotlin 中的字符串模板和日志框架的占位符有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71108049/

相关文章:

java - 尝试使用 Retrofit @Streaming 注释下载大文件时出现 OutOfMemoryError

logging - Windows 中的 Nginx $request_time 和 $upstream_response_time

java - 如何让 StringTemplate V4 忽略 < 作为分隔符?

Python String template dict KeyError,如何设置默认值

antlr - 字符串模板 : make all variable declaration global

spring - 使用 Kotlin BeanDefinitionDsl 时未调用 @PostConstruct

java - 如何从当前时间的开放时间开始/关闭

android - 在 kotlin 的 Elvis 运算符中使用多行

logging - 登录 lo4j/net 自定义附加程序的最佳实践

logging - 如何配置 WildFly 8.2.0 日志记录以仅显示调试级别的应用程序