javaspringlogginglogback

Set specific logback.xml file with -Dlogback.configurationFile when logback.xml is just in .war package


I have one logback.xml file and I want to split it per environment e.g dev, prod. I have found: How to use multiple configurations with logback in a single project?

and I see that I can do it via -Dlogback.configurationFile=/path/to/config.xml. That's great, but how to do it in good manner? I have spring application where logback-env.xml is under /src/main/resources. After deployment I just can find it in /deployedApp/users/myapp/com.myapp/10.0-SNAPSHOT/war/app/WEB-INF/classes/logback.xml. I also have a script which is setting all properties for tomcat and I can add it like this:

JAVA_OPTS="${JAVA_OPTS} -Dlogback.configurationFile=/deployedApp/users/myapp/com.myapp/10.0-SNAPSHOT/war/app/WEB-INF/classes/logback-dev.xml"

unfortunately it doesn't make sense for me because let's say that I will do some project structure change and will remove users from path or some other change. This will blow up.

What is the best way to specify with -Dlogback.configurationFile which logback-env.xml should be taken? How to pass path (which is changing during deployment) to logback.xml file to tomcat start script instead of hardcoding it?


Solution

  • project tree

    demo1
    └── src
        └── main
            ├── java
            │   └── com
            │       └── example
            ....
            ├── resources
            │   ├── application.properties
            │   └── logback.xml
            └── webapp
            ... 
    

    application.properties

    logging.config=${LOG_FILE_PATH:classpath:logback.xml}
    # export LOG_FILE_PATH=/my-conf-path/logback.xml
    

    Build War

    mvn clean package
    

    put war to Tomcat

    Test 1 - Default

    ./startup.sh
    

    Because the environment variable LOG_FILE_PATH has not been set, it will use the default value: classpath:logback.xml

    demo1.war will use

    apache-tomcat-10.1.28/webapps/demo1/WEB-INF/classes/logback.xml
    
    ./shutdown.sh
    

    Test 2 - Use Environment Variable

    export LOG_FILE_PATH=/your-path/conf/logback.xml
    
    ./startup.sh
    
    1. Use the same war file.

    2. If the environment variable (LOG_FILE_PATH) is not set, use logback.xml included in war.

    classpath:logback.xml mapping to

    1. If environment variables (LOG_FILE_PATH) are set, reference logback.xml according to the specified path.
    export LOG_FILE_PATH=/your-path/conf/logback.xml
    
    ./startup.sh