如何生成 multi-line 日志输出以强调例如更大操作的开始和结束

How to generate a multi-line logging output to emphasize for example the begin of a bigger action and the end of it

我曾经通过调用我自己的控制台实用程序方法来记录标题(例如更大动作的开始和结束):ConsoleUtil.printTitle("PDF Generation - Start"); 具有以下输出:

####################################################################################################
#                                PDF Generation  - Start - TimeStamp                               #
####################################################################################################

我自己的方法可以带几个参数,比如装饰字符,标题的宽度。 该方法显示标题居中

是否可以使用像 log4j2 这样的日志记录框架获得相同的输出?请循序渐进。

是否可以生成正常布局的日志和其他布局的标题等日志?

我对 log4j 和 log4j2 有一些背景知识。

提前致谢。

绝对有可能。我会为以上做的是

public class MyClass {
    static final Marker TITLE_MARKER = MarkerManager.getMarker("TITLE");
    private static final Logger LOGGER = LogManager.getLogger();

    public void main(String[] args) {
        logger.info(TITLE_MARKER, "PDF Generation - Start - Timestamp");
    }    
}

然后在您的 log4j2.xml 中您可以配置一个 MarkerPatternSelector

<Properties>
  <Property name="heading">##### as many #s as you want</Property>
  <Property name="spaces">                             </Property>
</Properties>
<Console name="Console" target="SYSTEM_OUT">
  <PatternLayout>
    <MarkerPatternSelector defaultPattern="[%-5level] %msg%n">
      <PatternMatch key="TITLE" pattern="[%-5level] ${heading}%n#${spaces}%msg%n${heading}%n"/>
    </MarkerPatternSelector>
  </PatternLayout>
</Console>

当在事件中使用 TITLE 标记时,MarkerPatternSelector 将使用 TITLE 的模式。所有其他事件将使用默认模式。

PatternSelectors 是插件,因此如果 Log4j 默认附带的插件不适合您,您始终可以创建自己的插件。

此外,Log4j 没有内置的方式来重复像开箱即用的 #s 这样的字符串。但是创建一个执行此操作的 RepeatLookup 并不困难。它与 UpperLookup 类似,但您可以使用 ${repeat:#,30} 之类的东西,然后查找方法将包含以下内容:

String[] parts = key.split(",");
if (parts.length != 2) {
  return key;
} 
return parts[0].repeat(Integer.parseInt(parts[1]);