gpt4 book ai didi

java - 需要帮助了解 Logback 的参数化日志记录优化

转载 作者:行者123 更新时间:2023-12-01 21:12:06 25 4
gpt4 key购买 nike

The logback parameterized logging docs says :

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

Only after evaluating whether to log or not, and only if the decision is positive, 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 when the log statement is disabled.

我对此的解释是,如果记录器设置为DEBUG,则根本不会评估entry。但这怎么可能呢?

换句话说,如果我写:

logger.debug("the entry is {}.", dbService.getEntry());

我假设如果记录器未设置为DEBUG,则不会调用dbService.getEntry()。我的理解正确吗?

最佳答案

该语句意味着格式化消息的构造,包括在 entry 上调用 toString() 的费用,仅当日志级别达到时才会发生已启用。 “参数构造”一词的选择具有误导性。仅指格式化消息的组装。

如果您的代码执行昂贵的操作来构造传递给记录器的值,那么无论是否启用日志级别,每次都会产生费用。例如

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

这是标准的 Java,没有什么神奇的事情发生。 someVeryExpectiveOperation() 每次都会被调用。

关于java - 需要帮助了解 Logback 的参数化日志记录优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40927005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com