《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