【发布时间】:2014-04-25 21:57:12
【问题描述】:
我想使用 LogJ4 2 中的 XML 配置文件登录到我的项目文件夹中的某个文件。这是一个共享项目,所以我不能只在所需位置的完整路径中编码。 该路径必须根据编译程序的机器是动态的,以便始终正确生成日志文件。
我在这里阅读了多种方法,但没有一种对我有用。
这是我的整体结构: 源:log.class 配置文件夹:log4j2.xml logs:我想把日志文件写在这里
XML 源代码如下所示:
<properties>
<property name="logFilePosition">${sys:logFilename}</property>
</properties>
和
<File name="OutputFile" fileName="${logFilePosition}" immediateFlush="true">
<PatternLayout>
<Pattern>%d{HH:mm:ss} %m; %n</Pattern>
</PatternLayout>
</File>
还有
<Root level="trace">
<AppenderRef ref="Console" level="trace" />
<AppenderRef ref="OutputFile" level="trace" />
</Root>
我也用fileName="${sys:logFilename}" 尝试过它也不起作用。
此 XML 不完整,但显示了相关部分。
我的 Log 类如下所示:
private static Logger logger = LogManager.getLogger(Log.class.getName());
LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
// Returns current location based on individual location
private static URL location = Log.class.getProtectionDomain().getCodeSource().getLocation();
private static String final_location = location.toString().substring(6, location.toString().length());
Log(){
// Sets system property required for XML configuration file in order to reference desired output location
// of log file by the use of "logFilename"
System.setProperty("logFilename", final_location+"logs/mylog.log");
//LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
ctx.reconfigure();
如果我只执行System.out.println(final_location+"logs/mylog.log");,则会显示正确的路径。如果我只是复制此路径并将其直接粘贴到 XML 文件中,则会生成一个日志文件。
问题似乎是在 Log() 构造函数之外,就像在此类中的其他方法中一样,属性“logFilename”为空。我怎样才能绕过这个?
我在这里缺少什么?我真的很感激任何帮助。
谢谢, 亚历克斯
【问题讨论】:
标签: xml eclipse logging log4j log4j2