How do I print an application version early in Spring Boot’s logs?… here is a solution to the problem.
How do I print an application version early in Spring Boot’s logs?
I tried to print my version of my application as early as possible in the log before any of my other code had a chance to execute, so that if an error occurs, that version is included in the log file.
@SpringBootApplication
public class Application {
public static void main( String... args ) {
var ctx = SpringApplication.run( Application.class, args );
ctx.getBeanProvider( BuildProperties.class ).ifAvailable( bp -> {
LogManager.getLogger( Application.class ).info( bp.getArtifact() );
} );
}
}
But the block in ifAvailable
is not executed, and I want to print the version in particular.
Note: This is done at build.gradle.kts
springBoot {
buildInfo() // generates BOOT-INF/classes/META-INF/build-info.properties
}
Update failed, there is no such bean….
@SpringBootApplication
public class Application {
public static void main( String... args ) {
SpringApplication.run( Application.class, args );
}
@Bean
CommandLineRunner runner( BuildProperties bp ) {
return args -> LogManager.getLogger( Application.class ).info( bp.getArtifact() );
}
}
Update 2: It doesn’t have to be after the banner, but it has to be early enough for it to print before any validations/errors in the custom code.
Solution
Let’s say you’re installing a jar (otherwise you need to make some modifications).
tasks.withType<BootJar>().configureEach {
enabled = true
manifest {
attributes(
"Implementation-Title" to project.description,
"Implementation-Version" to project.version
)
}
}
Then customize your banner.txt
; For example
${application.title} ${application.version}