📜 ⬆️ ⬇️

Logging Git revision in Java using Maven

Our company switched from mercurial to Git , after which I had to figure out how the information about the branch was displayed in our log and rewrite it under git. Maybe someone will face the same problem in the future, as Git is gaining popularity and many companies are migrating to it.

My goal is to show you how with the help of several maven plugins you can draw the name of a branch and hash of a commit from Git to the log of your java program. This is useful when analyzing logs, if you have not had a deployment for a long time and the history of your CI tool is lost.

Start


In my example I will use: java, maven, spring-core, git. Link to an example . Suppose that we already have a project written in Java and Maven is used for assembly, it is also stored on GitHub .

image

')

Maven scm


In order for maven to access your repository, you need to specify the methods and connection paths for it. To do this, use the maven scm :

... </dependencies> <scm> <connection>scm:git:https://github.com/<your_username>/<your_projectname>.git</connection> <developerConnection>scm:git:https://github.com/<your_username>/<your_projectname>.git</developerConnection> <tag>HEAD</tag> <url>https://github.com/<your_username>/<your_projectname>.git</url> </scm> <build> ... 

The access link is formed on the Git page of your project in the Quick setup section. More information about using scm and options for accessing the repository can be found here and here .

Getting information about the current git branch


Next we need to add the maven plugin buildnumber-maven-plugin , which will form the buildNumber - commit hash and scmBranch - the name of the branch.

 <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <version>1.4</version> <executions> <execution> <phase>validate</phase> <goals> <goal>create</goal> </goals> </execution> </executions> <configuration> <doCheck>false</doCheck> <doUpdate>false</doUpdate> </configuration> </plugin> 

The buildNumber and scmBranch formation takes place at the validate stage, which occurs after clean in Maven.

Options:


More information about this .

Work with properties


After that you can safely add the following variables to your application.properties file: $ {buildNumber} and $ {scmBranch}

For example, I added the following parameters to application.properties :

 branch.name=${scmBranch} commit.hash=${buildNumber} application.version=${project.version} 

In order for our application.properties to be found, add to the build tag:
 <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> 


Build project


Let's now build our project with the team:

 mvn clean install -DskipTests 

If you look at the log that maven brought you to build, you will notice that it executes the git command to get the required data:

 [INFO] --- buildnumber-maven-plugin:1.4:create (default) @ GitRevision --- [INFO] Executing: /bin/sh -c cd '/home/<user>/Development/GitRevision' && 'git' 'rev-parse' '--verify' 'HEAD' [INFO] Working directory: /home/<user>/Development/GitRevision [INFO] Storing buildNumber: 47c0d1df153b8610392d51d1a7fa0b7b39716e09 at timestamp: 1474375934082 [INFO] Storing buildScmBranch: master 

You can also check the correctness of the data in the target / classes folder application.properties file:

image

Content:

 branch.name=master commit.hash=47c0d1df153b8610392d51d1a7fa0b7b39716e09 application.version=0.0.1-SNAPSHOT 


Adding to the log


To get properties in any class with which spring works, the @Value annotation is used .

Example:

 public class LoggerExampleImpl implements LoggerExample { private static final Logger log = LoggerFactory.getLogger(LoggerExampleImpl.class); @Value("${branch.name}") private String branchName; @Value("${commit.hash}") private String commitHash; @Value("${application.version}") private String version; public void printLog() { log.info("Project version: {}, git branch: {}, commit hash: {}", version, branchName, commitHash); } } 

An example of a class with a main method:

 public class GitRevisionApplication { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); LoggerExample loggerExample = context.getBean(LoggerExampleImpl.class); loggerExample.printLog(); } } 

If we run our program, we get:

 2016-09-20 17:06:07 INFO [main] ClassPathXmlApplicationContext:581 - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@66cd51c3: startup date [Tue Sep 20 17:06:07 EEST 2016]; root of context hierarchy 2016-09-20 17:06:07 INFO [main] XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [spring.xml] 2016-09-20 17:06:07 INFO [main] PropertyPlaceholderConfigurer:172 - Loading properties file from URL [file:/home/rado/Development/GitRevision/target/classes/application.properties] 2016-09-20 17:06:08 INFO [main] LoggerExampleImpl:25 - Project version: 0.0.1-SNAPSHOT, git branch: master, commit hash: 52c05227fb27271314d80d39b5026193ff310f04 

Hash Reduction


The hash of our commit is too long, in order to cut it you need to specify in the buildnumber-maven-plugin the maximum number of characters we want to output:

  <configuration> <shortRevisionLength>5</shortRevisionLength> </configuration> 

Extend git with MANIFEST.MF


It is possible to add this data to MANIFEST.MF. For this we need to connect another maven plugin: maven-jar-plugin .

 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> </manifest> <manifestEntries> <Implementation-Version>${project.version}-${buildNumber}</Implementation-Version> <Implementation-Build>${scmBranch}</Implementation-Build> <Main-Class>com.habrahabr.example.GitRevisionApplication</Main-Class> </manifestEntries> </archive> </configuration> </plugin> 

After assembling our project, we will be able to see in MANIFEST.MF :

 Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: rado Build-Jdk: 1.8.0_102 Specification-Title: GitRevision Specification-Version: 0.0.1-SNAPSHOT Implementation-Title: GitRevision Implementation-Vendor-Id: com.habrahabr.example Implementation-Build: master Implementation-Version: 0.0.1-SNAPSHOT-47c0d1df153b8610392d51d1a7fa0b7 b39716e09 Main-Class: com.habrahabr.example.GitRevisionApplication 

Thank. I hope the article will be useful.

Source: https://habr.com/ru/post/310738/


All Articles