Search code examples
javalogginglog4jlogback

how to get maven project version in logback.xml


how can i get the maven project version in logback configuration file since I want to log the project version number. here is the maven file.

<groupId>com.shanil</groupId>
<artifactId>loggingDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>loggingDemo</name>
<description>Demo project for Spring Boot logging</description>

here is the logback configuration file

 <appender name="Console"
    class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.classic.PatternLayout">
        <Pattern>
            CEF:1|CompanyTest|%X{nameofapplication:-loggingDemo}|**version number here**| %msg%n 
        </Pattern>
    </layout>
</appender>

Solution

  • You could have a build step which takes a template logback file and populates some placeholders. From logback's perspective, the version would then just be an arbitrary string, just like the CEF:1|CompanyTest| part.

    Maven resources plugin should be able to achieve this. It uses "filtering" to replace placeholders.

    <build>
        <resources>
            <resource>
                <includes>
                    <include>some/dir/logback.template.xml</include>
                </includes>
                <targetPath>some/outputpath/logback.xml</targetPath>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    

    Your logback template would look something like this

    <Pattern>
        CEF:1|CompanyTest|%X{nameofapplication:-loggingDemo}|${project.artifact.id}| %msg%n 
    </Pattern>
    

    You might want to play around with changing the delimiter; not sure whether the default format ${...} will mix well with logback's format {...}. So you could change the delimiter to ** or something.