Load log4j.properties with JAR [duplicate]

2019-03-15 04:01发布

问题:

This question already has an answer here:

  • Should log4.properties be on the classpath? 6 answers

I have a jar file with the following Manifest

Manifest-Version: 1.0  
Created-By: 1.7.0_07 (Oracle Corporation)  
Main-Class: test.Main  
Class-Path: ./log4j.properties lib/log4j-1.2.17.jar 

I run the class as follows

java -jar test.jar

And this is my folder

lib
log4j.properties
test.jar

Why I can't see the log4j properties file? This is what I see

log4j:WARN No appenders could be found for logger (test.Main).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Thank you

SOLUTION: changed my classhpath in the MANIFEST to this

Class-Path: . lib/log4j-1.2.17.jar 

回答1:

You can also start your JVM with argument:

-Dlog4j.configuration=file:"./your/properties/path/log4j.properties"

to specify arbitrary location of your external log properties. I used this a lot in one particular project.



回答2:

Properties file doesn' go in classpath, you must provide it and call it from code as shown here.

EDIT: With your directory structure you call it like this:

PropertyConfigurator.configure("log4j.properties");

EDIT2:

Also, you must provide appender for it:

log4j.rootLogger=DEBUG, Appender1
log4j.logger.[logger-name]=level, Appender1
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

If you want finer control over logging, remove the first line (root looger) and put the second one where instead of [logger-name] you put the topmost package so that all the classes inside that package can use logging.

You can define multiple appenders and assign them to different classes in that manner.



回答3:

PropertyConfigurator.configure(ABC.class.getResourceAsStream("log4j.properties")) worked me correctly, but basically you need to place Log4j properties file in Source Code folder (next to Java Class).

OR you can try putting outside and give proper path in getResourceAsStream("resources/log4j.properties") method



标签: java jar log4j