在slf4j中使用decimalformat或logback来填充或识别号码,使它们对齐

Geo*_*met 5 java logging logback slf4j

我在SLF4J中有这个日志语句(在它下面有Logback):

        logger.info("{} has {} depots, {00} vehicles and {} customers with a search space of {}.", ...);
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

A-n62-k8 has 1 depots, 8 vehicles and 61 customers with a search space of 10^108.
A-n63-k10 has 1 depots, 10 vehicles and 62 customers with a search space of 10^111.
Run Code Online (Sandbox Code Playgroud)

但我想要这个输出,它增加了额外的空间填充/缩进:

A-n62-k8  has 1 depots,  8 vehicles and 61 customers with a search space of 10^108.
A-n63-k10 has 1 depots, 10 vehicles and 62 customers with a search space of 10^111.
Run Code Online (Sandbox Code Playgroud)

这可能与SLF4J一起使用吗?

小智 4

看来没有。您应该对每个必须带有额外空格的参数使用 String.format(...) 。像这样的东西

logger.info("{} has {} depots, {} vehicles and {} customers with a search space of {}.", String.format("%-9s", "A-n62-k8"), "1", String.format("%-2s", "8"), "61", "10^108");
Run Code Online (Sandbox Code Playgroud)

  • 同意,但这会比较慢,因为即使未打开信息日志记录,也会产生 String.format() 成本。 (3认同)
  • 您还会收到 SonarLint 警告 https://rules.sonarsource.com/java/RSPEC-2629 并且有充分的理由。如果你有 log.debug,即使调试关闭,你也会执行填充 (2认同)