javaspring-bootlogbacklogstash-logback-encoder

How to output git commit id to all logback logs with Spring Boot?


I am using SpringBoot with Logback along with the git commit id maven plugin. How do I configure logback and SpringBoot to include the git commit id that the actuator returns in my log output? I want each line of output to include the git commit id of the boot app that generated the line of output.


Solution

  • By default, the git-commit-id-plugin creates a file named git.properties in the root of the classpath containing lots of properties, including git.commit.id.

    You can import these properties in logback's config file, and access the properties anywhere within the logback configuration.

    For example, you can use it within a pattern like this:

    <configuration>
    
        <!-- Expose the properties from the file generated by git-commit-id-plugin -->
        <property resource="git.properties"/>
    
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} ${git.commit.id} - %message%n</pattern>
            </encoder>
        </appender>
        ...
    </configuration>
    
    

    Or (since you tagged this question with logstash-logback-encoder) you can include it in a JSON field via custom fields, or via the pattern provider like this:

    <configuration>
    
        <!-- Expose the properties from the file generated by git-commit-id-plugin -->
        <property resource="git.properties"/>
    
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
                <providers>
                    <pattern>
                        <pattern>{"commitId":"${git.commit.id}"}</pattern>
                    </pattern>
                ...
                </providers>
            </encoder>
        </appender>
        ...
    </configuration>