Logger 日志输出请使用占位符 {}

2023-03-13 09:17:48

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方法,而第一种非debug级别也会执行。
原因2,更具可读性。

写代码要多注意这些细节。

  • 作者:Star--Zhang
  • 原文链接:https://blog.csdn.net/cyuanxin/article/details/51591848
    更新时间:2023-03-13 09:17:48