How to configure log4j with a properties file

前端 未结 9 1916
春和景丽
春和景丽 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:33

    This is an edit of the answer from @kgiannakakis: The original code is wrong because it does not correctly close the InputStream after Properties.load(InputStream) is called. From the Javadocs: The specified stream remains open after this method returns.

    ================================

    I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:

    Properties props = new Properties();
    InputStream is = new FileInputStream("log4j.properties");
    try {
        props.load(is);
    }
    finally {
        try {
            is.close();
        }
        catch (Exception e) {
            // ignore this exception
        }
    }
    PropertyConfigurator.configure(props);
    

    If the properties file is in the jar, then you could do something like this:

    Properties props = new Properties();
    InputStream is = getClass().getResourceAsStream("/log4j.properties");
    try {
        props.load(is);
    }
    finally {
        try {
            is.close();
        }
        catch (Exception e) {
            // ignore this exception
        }
    }
    PropertyConfigurator.configure(props);
    

    The above assumes that the log4j.properties is in the root folder of the jar file.

提交回复
热议问题