14

I'm using Apache Commons Logging and SLF4J with log4j, but I also want to use the log4j.properties in a custom place like conf/log4.properties. Here is the problem:

If i use

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

then my app is tied to log4j and defeats the purpose of having ACL and SLF4J.

What is the best way to configure it without the app ever knowing what the logging implementation is?

Azder
  • 4,698
  • 7
  • 37
  • 57

3 Answers3

26

I think the easiest thing to do is specify the location of the file using the log4j.configuration system property. Adopting the example in the Log4J manual:

java -Dlog4j.configuration=conf/log4j.properties -classpath ...

I believe that Log4J will find a file named "log4j.properties" anywhere on the classpath, but may be hallucinating. Worth trying, however.

kdgregory
  • 38,754
  • 10
  • 77
  • 102
  • 9
    Actually, I had the same problem as the OP, but your solution didn't work for me. I had to specify the location of the log4j.properties file in a URL style form (-Dlog4j.configuration=file:///my/conf/log4j.properties). – Haes Oct 27 '09 at 14:22
  • 1
    Upvotes all round. Worked for me with only one forward slash after file: -Dlog4j.configuration=file:/C:/JBoss51/jboss-eap-5.1/..../log4j.properties on JBOSS 5.1 EAP on a Windows 7 machine. – CodeClimber Oct 05 '12 at 10:50
  • @kdgregory...where do we specify the location of file, is it in VM arguments in RUN configuration in eclipse project OR is it a configuration file in tomcat ? – MKod May 20 '16 at 18:31
  • @Haes This is solution for me too, should be also the accepted answer. Thanks :) – Frankie Drake Jun 25 '17 at 12:09
  • This didn't work for me on Linux. I had to add file: (E.g., java -Dlog4j.configuration=file:/path/to/log4j.properties -classpath ...) – leeman24 Dec 06 '17 at 17:50
3

As you state, by invoking PropertiesConfigurator, you are tying your application to log4j. However, the extend of this tie is quite limited. You could very easily remove the line invoking PropertiesConfigurator and recompile your code. After that is done, assuming you are using the SLF4J API for logging, you could repalce log4j with another logging framework, say logback-classic or j.u.l. just by replacing jar files. Thus, SLF4J still serves its purpose to a large extend. I would not throw the baby out with the bath water.

Ceki
  • 26,753
  • 7
  • 62
  • 71
1

You can specify config file location with VM argument

-Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"

ring bearer
  • 20,383
  • 7
  • 59
  • 72
Makatun
  • 947
  • 10
  • 11