I have been trying to get log4j-2.0-b9 to work with a jar but haven't been able to. I want the properties file outside the .jar and in the same directory as the .jar file but log4j doesn't seem to pick it up and defaults to printing on the console. My configuration file looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
                 xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>
  </layout>
</appender>

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
  <param name="append" value="false"/>
  <param name="file" value="C:\Users\abhishek\workspace\log4jtest\log.log"/>
  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
  </layout>
</appender>

 <root>
  <level value="ALL"/>

  <appender-ref ref="fileAppender"/>
 </root>

</log4j:configuration>

And my JAVA code looks like:

package com.test;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Test {

private static Logger logger = LogManager.getLogger(Test.class);

public static void main(String[] args) {
    logger.error("Test error");
}
}

Thanks.

有帮助吗?

解决方案

The configuration in the question uses the log4j-1.2 format. Log4j-2.0 uses a different XML format. The configuration file should also be called log4j2.xml instead of log4j.xml. The easiest way to configure is to put the log4j2.xml file in the classpath.

The online docs have many example configurations: for example for File Appender, and the Console.

Note that you need both the log4j-api-2.0 and log4j-core-2.0 jar files in the classpath.

其他提示

The log4j configuration file needs to be in the classpath to be seen. If you're running java from a jar, then that jar file is your classpath, so the log4j configuration will have to be in that jar.

If you don't want to do that, perhaps you can add the "Class-Path" header to the manifest of the jar file. I haven't tried that myself, but it's described here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top