Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading log4j properties from a package in java

In my java swing application I load log4j properties from a properties file stored in a package in the application and I load that properties file as,

try {                            
     PropertyConfigurator.configure("conf/log4j.properties");
     logger.info("Starting the system.");                           

} catch (Exception e) {
     e.printStackTrace();

}

Then I get following error when the application is starts,

log4j:ERROR Could not read configuration file [conf/log4j.properties].
java.io.FileNotFoundException: conf/log4j.properties (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileInputStream.<init>(FileInputStream.java:97)
        at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:297)
        at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:315)
        at com.bio.ofm.mnu.views.SplashScreen$1.run(SplashScreen.java:70)
        at java.lang.Thread.run(Thread.java:722)
log4j:ERROR Ignoring configuration file [conf/log4j.properties].
log4j:WARN No appenders could be found for logger (com.bio.ofm.mnu.views.SplashScreen).
log4j:WARN Please initialize the log4j system properly.

Is this way of loading property file is wrong? please help.

I build a .jar file and run the application using that jar**

like image 597
Harsha Avatar asked May 24 '12 02:05

Harsha


Video Answer


3 Answers

If conf is the source folder you can use:

PropertyConfigurator.configure("classpath:conf/log4j.properties");

else you can try this:

PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("conf/log4j.properties"));
like image 159
Diego D Avatar answered Oct 26 '22 12:10

Diego D


The LogManager automatically class will look for a file named log4j.properties or log4j.xml in the classpath used for loading the log4j classes. Up to version 1.2.6, log4j would look for only the log4j.properties file in the classpath. Since version 1.2.7, log4j looks for both log4j.properties and log4j.xml in the classpath.

Simply place log4j file in the default package. You should also make sure that the file is in directory of .class.

like image 28
Paul Vargas Avatar answered Oct 26 '22 13:10

Paul Vargas


I use the Rachel java library http://rachel.sourceforge.net/ a lot for this kind of stuff

Download the lib and add it to your class path. Then you can use it like so to load any file from a JAR file / package and it also work when using JNLP deployed applications. They have a lot of good tutorials to read on the best way to load your file. I usually like to load them as inputstreams.

like image 45
george_h Avatar answered Oct 26 '22 13:10

george_h