Search code examples
javamavenlogginglogback

Unable to configure Logback from a custom directory using the logback.configurationFile parameter


I want to change the default directory of the logback.configurationFile in order to give a new directory to it so that it looks for logback.xml in that directory but it doesn't work. How can I do that?

public class App{
    static{System.setProperty("logback.configurationFile","C:/Users/p.khaleghi/");}
    public static void main(String args[]) {


        if(args[0] == null){
            System.out.println("There is no input file in the right directory");
        }
        else{
            Calculator calculator = new Calculator();
            calculator.calculate(args[0]);
        }

    }
}

Solution

  • The logback.configurationFile system property is a path to a configuration file, it is not a path to a directory which might contain a configuration file.

    So, assuming there is a file named other-logback.xml in this directory: C:/Users/p.khaleghi/ then you can tell Logback to configure itself from that file by either:

    • Running with the following JVM system parameter: -Dlogback.configurationFile=C:/Users/p.khaleghi/other-logback.xml

    • Using a static initialiser in your class to set that system property: static{System.setProperty("logback.configurationFile","C:/Users/p.khaleghi/other-logback.xml");}. Note: this approach will only work if this static initialiser runs before Logback is initiaised so if you had this static initialiser and a static Logger declaration in the same class then Logback could be initialised before the logbackConfigurationFile property is set.

    More details in the docs