Trying to inject properties defined in application.properties/application.yml
into logback.groovy
script in Spring Boot project.
I cannot Inject Environment
or ApplicationContext
into groovy scripts.
Are there any workarounds?
I am not looking for solutions like System.getProperty('spring.profiles.active')
src/main/resources/logback.groovy
import org.springframework.core.env.Environment
@Inject private Environment env; //this is not working. how to get env here?
println "spring.profiles.active : ${env.getProperty('spring.profiles.active')}"
appender("STDOUT", ConsoleAppender) {
encoder(PatternLayoutEncoder) {
pattern = "%green(%d{HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n"
}
}
if(System.getProperty("spring.profiles.active")?.equalsIgnoreCase("prod")) {
root INFO, ["STDOUT", "FILE"]
} else {
root INFO, ["STDOUT"]
}
src/main/resources/application.yml
---
spring:
profiles:
active: development
logback.groovy needs to be evaluated very early because otherwise the code for loading the spring configuration, instantiating beans, etc. could not log anything. That's why @Inject can't work.
I see 2 options:
A different approach is to externalize the logback configuration on production with -Dlogback.configurationFile=/path/to/config.groovy. Putting the config file in a well known location (like /etc/my-app) makes it easy to change log levels in production without re-deploying (or even re-starting).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With