Logger 日誌輸出請使用 {}
阿新 • • 發佈:2019-01-30
review程式碼時,發現太多人習慣log日誌直接用“+”號連線。這是很不好的習慣。
In Logger, the logging methods are overloaded with forms that accept one, two or more values.[9] Occurrences of the simple pattern {} in the log message are replaced in turn with the values. This is simple to use yet provides a performance benefit when the values have expensive toString() methods. When logging is disabled at the DEBUG level, the logging framework does not need to evaluate the string representation of the values. In the following example, the values count or userAccountList only need to be evaluated when DEBUG is enabled; otherwise the overhead of the debug call is trivial.
private static final Logger LOG = LoggerFactory.getLogger(Wombat.class);
LOG.debug("There are now " + count + " user accounts: " + userAccountList); // slow
LOG.debug("There are now {} user accounts: {}", count, userAccountList); // faster
如上面demo,請選擇第二種書寫方式。
原因1,看引用,在有debug輸出時,才會進行count,和userAccountlist的toString,否則忽略。
原因2,更具可讀性。
寫程式碼要多注意這些細節。