部署服务后Logback无法引用生成的git.properties问题排查
git.commit.id.abbrev在非dev环境显示unknown的原因 1. 打包阶段插件目标未正确执行
非dev环境的Maven打包命令或自定义Profile可能跳过了git-commit-id-maven-plugin的执行。检查插件配置,确保其绑定到package阶段(而非仅compile阶段),且未被环境Profile禁用:
<plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-maven-plugin</artifactId> <version>6.0.0</version> <executions> <execution> <id>fetch-git-info</id> <goals> <goal>revision</goal> </goals> <phase>package</phase> <!-- 绑定到打包阶段,确保每次打包都生成配置 --> </execution> </executions> </plugin>
2. 部署包中缺失git.properties
部分CI/CD流程可能在打包后修改了部署包(如清理非必要文件),导致git.properties被移除。解压部署后的jar/war包,检查BOOT-INF/classes(Spring Boot jar)或对应classes目录下是否存在该文件,且文件内包含git.commit.id.abbrev字段及有效值。
3. Logback加载时机与配置方式问题
Spring的springProperty标签在Logback初始化时,Spring上下文可能尚未完全加载git.properties的配置。可以直接用Logback原生的property标签读取配置文件,避免加载顺序问题:
<!-- 直接读取classpath下的git.properties --> <property resource="git.properties"/> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - gitCommitId: ${git.commit.id.abbrev:-unknown} %msg%n</pattern> </encoder> </appender>
4. 插件配置过滤了目标字段
检查插件配置,确认未通过excludeProperties禁用git.commit.id.abbrev的生成,或通过includeProperties明确包含该字段:
<plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-maven-plugin</artifactId> <version>6.0.0</version> <configuration> <includeProperties> <includeProperty>git.commit.id.abbrev</includeProperty> </includeProperties> <!-- 若CI环境无完整Git仓库,需允许插件跳过Git检查并设置默认值 --> <failOnNoGitDirectory>false</failOnNoGitDirectory> <defaultProperties> <git.commit.id.abbrev>unknown</git.commit.id.abbrev> </defaultProperties> </configuration> </plugin>
如果非dev环境是干净的代码拉取(未初始化Git仓库),插件无法获取提交ID,需开启failOnNoGitDirectory=false并配置默认值。
5. 环境变量或配置优先级冲突
非dev环境的系统环境变量可能存在同名配置git.commit.id.abbrev=unknown,导致Spring优先读取环境变量而非git.properties。可以在启动时添加参数-Dspring.config.location=classpath:/git.properties强制指定加载顺序,或检查环境变量列表排除冲突项。
内容的提问来源于stack exchange,提问作者mal

