如何在没有字符串拼接的情况下改进日志机制呢?
考虑以下示例:
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggerTest {
public static void main(String[] args) {
// get logger
Logger log = Logger.getLogger(LoggerTest.class.getName());
// set log level to INFO (so fine will not be logged)
log.setLevel(Level.INFO);
// this line won't log anything, but will evaluate the getValue method
log.fine("Trace value: " + getValue());
}
// example method to get a value with a lot of string concatenation
private static String getValue() {
String val = "";
for (int i = 0; i < 1000; i++) {
val += "foo";
}
return val;
}
}
log.fine(...)
方法不会记录任何内容,因为日志级别已设置为 INFO
。问题在于,getValue
方法仍将被评估。
对于具有许多调试语句的大型应用程序,这是一个性能问题。
那么,如何解决这个问题呢?
log.fine("Trace value: {}", getValue());
它在任何情况下都会评估getValue
方法,不是吗? - bobbel