我们可以在 log4j 信息中包含构建日期和版本吗

我想在日志语句中包含构建信息(构建版本、日期)。这能做到吗?我在 Java 8 应用程序中使用 log4j。

liulinjian123 回答:我们可以在 log4j 信息中包含构建日期和版本吗

您可以在日志语句中包含构建日期和版本。

为了实现这一点,您需要使用两件事

  1. 动态或从文件中获取构建日期和版本
  2. 更新日志记录模式

构建插件配置:如果你使用的是 Spring Boot,你的 pom.xml 应该有

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>build-info</id>
            <goals>
                <goal>build-info</goal>
            </goals>
        </execution>
    </executions>
</plugin>

访问构建属性:配置 spring-boot-maven-plugin 并构建应用程序后,您可以通过 BuildProperties 对象访问有关应用程序构建的信息。

@Autowired
BuildProperties buildProperties;

获取值

buildProperties.getName(); // Artifact's name from the pom.xml file    
buildProperties.getVersion(); // Artifact version    
buildProperties.getTime(); // Date and Time of the build    
buildProperties.getArtifact(); // Artifact ID from the pom file    
buildProperties.getGroup(); // Group ID from the pom file

使用 ThreadContext 或 MDC 添加值

MDC.put("build_date",buildProperties.getTime());
MDC.put("build_version",buildProperties.getVersion());

更新日志模式:示例模式

#注意 %X{userName} - 这是从映射诊断上下文 (MDC) 获取数据的方式

log4j.appender.consoleAppender.layout.ConversionPattern = %-4r [%t] %5p %c %x - %m - %X{build_date} - %X{build_version}%n
,

您可以使用 lookups 来完成。您可以使用以下内容存储构建日期:

org.apache.logging.log4j.ThreadContext.put("buildDate","01/01/1970");

然后在您的 log4j 配置中使用它,如下所示:

<File name="Application" fileName="application.log">
  <PatternLayout>
    <pattern>%d %p %c{1.} [%t] $${ctx:buildDate} %m%n</pattern>
  </PatternLayout>
</File>

与版本相同。在我的示例中,我对日期值进行了硬编码,但您可以从配置文件或环境变量等中检索它。

本文链接:https://www.f2er.com/45333.html

大家都在问