How to configure log4j with a properties file

前端 未结 9 1917
春和景丽
春和景丽 2020-11-29 03:01

How do I get log4j to pick up a properties file.

I\'m writing a Java desktop app which I want to use log4j. In my main method if have this:

   Proper         


        
9条回答
  •  甜味超标
    2020-11-29 03:43

    When you use PropertyConfigurator.configure(String configFilename), they are the following operation in the log4j library.

    Properties props = new Properties();
    FileInputStream istream = null;
    try {
      istream = new FileInputStream(configFileName);
      props.load(istream);
      istream.close();
    }
    catch (Exception e) {
    ...
    

    It fails in reading because it looks for "Log4j.properties" from the current directory where the application is executed.

    How about the way that it changes the reading part of the property file as follows, and puts "log4j.properties" on the directory to which the CLASSPATH is set.

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource("log4j.properties");
    PropertyConfigurator.configure(url);
    

    Another method of putting "Log4j.properties" in the jar file exists.

    jar xvf [YourApplication].jar log4j.properties
    

提交回复
热议问题