Springboot中获取git提交信息,通过springboot actuator的/info endpoint查看
《Springboot Actuator之二:actuator在监控和管理指标的特性》
《Springboot中获取git提交信息,通过springboot actuator的/info endpoint查看》
项目中的代码放git上管理,jenkins的CICD的流水线打包发布下,经常容易忘记提交代码或者合并分支等。导致调试时和预期不一致,如果把代码的git提交记录在运行时展示出来,就可以快速确认是否是环境部署的问题导致的。
build.gradle中增加
plugins { id "com.gorylenko.gradle-git-properties" version "1.5.1" }
java代码:
@Slf4j @Component public class GitCommitInfoApplicationRunner implements ApplicationRunner { @Value("${spring.application.name:}") private String applicaitonName; @Override public void run(ApplicationArguments args) throws Exception { try { Resource resource = new ClassPathResource("git.properties"); Properties properties = new Properties(); properties.load(new InputStreamReader(resource.getInputStream())); log.info("{}打包日志: 分支[{}],代码版本[{}],构建时间[{}],提交时间[{}]", applicaitonName, properties.getProperty("git.closest.tag.name"), properties.getProperty("git.commit.id.abbrev"), properties.getProperty("git.build.time"), properties.getProperty("git.commit.time")); log.info("{}-GitCommitInfo: [{}]", applicaitonName, properties); } catch (FileNotFoundException e) { log.warn("git.properties文件不存在"); } catch (IOException e) { log.warn("git.properties文件读取失败"); } } }
二、/info的endpoint如何读取git信息的呢?
重写:
public class GitInfoContributor extends InfoPropertiesInfoContributor<GitProperties> { public GitInfoContributor(GitProperties properties, Mode mode) { super(properties, mode); } public GitInfoContributor(GitProperties properties) { this(properties, Mode.SIMPLE); } @Override public void contribute(Info.Builder builder) { builder.withDetail("git", generateContent()); } @Override protected PropertySource<?> toSimplePropertySource() { Properties props = new Properties(); copyIfSet(props, "branch"); String commitId = getProperties().getShortCommitId(); if (commitId != null) { props.put("commit.id", commitId); } copyIfSet(props, "build.time"); copyIfSet(props, "build.user.email"); copyIfSet(props, "build.version"); copyIfSet(props, "closest.tag.name"); copyIfSet(props, "commit.id.abbrev"); copyIfSet(props, "commit.id.describe"); copyIfSet(props, "commit.message.full"); copyIfSet(props, "commit.message.short"); copyIfSet(props, "commit.user.email"); copyIfSet(props, "commit.time"); copyIfSet(props, "remote.origin.url"); return new PropertiesPropertySource("git", props); }
参考:
https://www.dazhuanlan.com/booknect/topics/1506785