java 配置 Log4j 属性路径的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4825414/
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
Best Practice on Configuring Log4j Properties Path
提问by Sandeep Jindal
I am using Log4j in my applications. log4j.properties
is placed in a Jar which is in classpath. This configuration file is being used and works fine most of the times.
我在我的应用程序中使用 Log4j。log4j.properties
放置在类路径中的 Jar 中。这个配置文件正在被使用并且在大多数情况下都可以正常工作。
But sometimes, the logging statements that are getting generated are not as per the configuration file.
但有时,生成的日志语句与配置文件不同。
My understanding is, this is because the properties file is fetched from the class path. Whatever first properties file is, is fetched and used by log4j. Thus sometimes we get the logging statements different from what is configured in properties file.
我的理解是,这是因为属性文件是从类路径中获取的。无论第一个属性文件是什么,都会被 log4j 获取和使用。因此有时我们得到的日志语句与属性文件中配置的不同。
In case, the above reason is true, then I think, we need to specify the configuration file specifically by one of the following ways:
如果上述原因成立,那么我认为,我们需要通过以下方式之一来具体指定配置文件:
- Specify using System Properties : -Dlog4j.configuration=log4j.properties
- Initializing Log4jInit servlet.
- 使用系统属性指定:-Dlog4j.configuration=log4j.properties
- 初始化 Log4jInit servlet。
Please suggest which could be the better approach.
请建议哪个可能是更好的方法。
回答by Jigar Joshi
In my application I am using ${user.home}
dir to store log4j.properties
and using ant we are reading it. it will be platform independent. also you can pass one with build in classpath but reading from ${user.home} is better approach, You or any non technical person can easily access it.
在我的应用程序中,我使用${user.home}
dir 来存储log4j.properties
和使用我们正在阅读的 ant。它将是平台独立的。您也可以通过内置类路径传递一个,但从 ${user.home} 读取是更好的方法,您或任何非技术人员都可以轻松访问它。
also you can use
你也可以使用
Dynamic Log File Location
Many people complain that Log4j forces you to hard-code the location where your logs will be kept. Actually, it is possible to dynamically choose the log-file location, especially if you use the ${log.dir} property substitution technique above. Here's how:
动态日志文件位置
许多人抱怨 Log4j 强迫您对保存日志的位置进行硬编码。实际上,可以动态选择日志文件位置,特别是如果您使用上面的 ${log.dir} 属性替换技术。就是这样:
String dynamicLog = // log directory somehow chosen...
Properties p = new Properties( Config.ETC + "/log4j.properties" );
p.put( "log.dir", dynamicLog ); // overwrite "log.dir"
PropertyConfigurator.configure( p );
Also See
另见
回答by Chris Nava
When searching for items on the classpath the firstinstance of file with a matching name is used. So add your .jar to the front.
在类路径上搜索项目时,将使用具有匹配名称的文件的第一个实例。因此,将您的 .jar 添加到前面。
set CLASSPATH=myfile.jar;%CLASSPATH%