Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
Luis Trigueiros Avatar asked Jan 26 '23 01:01

Luis Trigueiros


2 Answers

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. the set env var MICRONAUT_ENVIRONMENTS=dev according to your deployment logic.

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

like image 97
erik.aortiz Avatar answered Jan 28 '23 15:01

erik.aortiz


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.

like image 28
patelb Avatar answered Jan 28 '23 16:01

patelb