Mohammad Gouse
Mohammad Gouse

Reputation: 365

Not able to load LOG4J2.xml File from system environment variable

I am doing a web application using Tomcat in eclipse and I kept the log4j2.xml file in environment variable location.

using System environment variable

Variable name : sys_logroot
Variable value : D:\user\gouse

In this directory I have my log4j2.xml file.I am trying to use this log4j2.xml file in my application I am not able to load this xml file and no log files are created to my application.

How can I load an Log4j2.xml file into my application to get logs for my application?

Upvotes: 2

Views: 2374

Answers (1)

alex555
alex555

Reputation: 1786

Apache says (from here):

How do I specify the configuration file location?

By default, Log4j looks for a configuration file named log4j2.xml (not log4j.xml) in the classpath.

You can also specify the full path of the configuration file with this system property: -Dlog4j.configurationFile=path/to/log4j2.xml

i.e. you have to set the system property at runtime to let log4j use it. Something like this:

    String value = System.getenv("sys_logroot");
    value = "file:" + value;
    System.setProperty("log4j.configurationFile", value);

Important is to call this part before using classes logging. Here is my test code:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {

  private static final Logger logger = LogManager.getLogger(Main.class.getName());

  public void doSomething() {
    logger.debug("Do something");
  }
}

Tester:

public class Tester {
public static void main(String[] args) {

String value = System.getenv("sys_logroot");
value = "file:" + value;
    System.setProperty("log4j.configurationFile", value);

    new Main().doSomething();
 }
}

Upvotes: 1

Related Questions