Java 自定义位置中的 Log4j 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/875663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Log4j Properties in a Custom Place
提问by Azder
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:
我将 Apache Commons Logging 和 SLF4J 与 log4j 一起使用,但我也想在自定义位置(如 conf/log4.properties)中使用 log4j.properties。这是问题所在:
If i use
如果我使用
PropertyConfigurator.configure("conf/log4j.properties");
then my app is tied to log4j and defeats the purpose of having ACL and SLF4J.
然后我的应用程序绑定到 log4j 并破坏了拥有 ACL 和 SLF4J 的目的。
What is the best way to configure it without the app ever knowing what the logging implementation is?
在应用程序不知道日志实现是什么的情况下配置它的最佳方法是什么?
采纳答案by kdgregory
I think the easiest thing to do is specify the location of the file using the log4j.configurationsystem property. Adopting the example in the Log4J manual:
我认为最简单的方法是使用log4j.configuration系统属性指定文件的位置。采用Log4J 手册中的示例:
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.
我相信 Log4J 会在类路径的任何位置找到一个名为“log4j.properties”的文件,但可能会产生幻觉。不过值得一试。
回答by Ceki
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.
正如您所说,通过调用PropertiesConfigurator
,您将应用程序绑定到 log4j。然而,这种关系的延伸是相当有限的。您可以非常轻松地删除调用行PropertiesConfigurator
并重新编译您的代码。完成后,假设您使用 SLF4J API 进行日志记录,您可以将 log4j 替换为另一个日志记录框架,例如 logback-classic 或 jul,只需替换 jar 文件即可。因此,SLF4J 在很大程度上仍然发挥着它的作用。我不会把婴儿和洗澡水一起倒掉。
回答by Makatun
You can specify config file location with VM argument
您可以使用 VM 参数指定配置文件位置
-Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"
-Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"