I would like to configure logging appender based on the environment, for example while running in production I would like to configure an appender that would send log to elasticsearch but while on test or development mode this appender would not be enabled.
You can override the default logback config file by using "logback.configurationFile" system variable.
java -Dlogback.configurationFile=logback-prod.xml -jar your.jar
But, if what you need is the ability to use an env variable you can do this without to use a third-party library:
Override the logback system variable inside the main micronaut class before call main, like following
@Singleton
public class MyMicronautApplication {
public static void main(String[] args) {
var env = System.getenv("MICRONAUT_ENVIRONMENTS");
if (env != null && !env.isEmpty()) {
System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "logback-" + env + ".xml");
}
Micronaut.run(MyMicronautApplication.class);
}
}
create you custom env based logback config file like: logback-dev.xml and put in resources dir.
the set env var MICRONAUT_ENVIRONMENTS=dev according to your deployment logic.
enjoy using logback-dev.xml, logback-prod.xml, logback-stagging.xml, etc
The work around i found was by doing conditional expressions in logback. You will need the following dependency
<!-- https://mvnrepository.com/artifact/org.codehaus.janino/janino -->
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.1.2</version>
</dependency>
Then in your logback.xml
file, you can do a conditional statement such as following for selecting the appender you want to you use based on a micronaut profile. In my case, I wanted to activate the STDOUT
appender if i was running the application locally but i did not want to activate the STDOUT
profile if the app was running in any other environment such as dev or prod profiles, instead i wanted the RSYSLOG
appender to be used.
<root level="info">
<if condition='property("MICRONAUT_ENVIRONMENTS").contains("local")'>
<then>
<appender-ref ref="STDOUT"/>
</then>
<else>
<appender-ref ref="RSYSLOG"/>
</else>
</if>
</root>
You can use conditional statements to configure other properties in your logback file.
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