Search code examples
logbackmicronaut

Micronaut configure logger appenders based of the enviroment


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.


Solution

  • 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:

    1. 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);
      
           }
       }
      
    2. create you custom env based logback config file like: logback-dev.xml and put in resources dir.

    3. then set env var MICRONAUT_ENVIRONMENTS=dev according to your deployment logic.

    4. enjoy using logback-dev.xml, logback-prod.xml, logback-stagging.xml, etc