我是Log4j API的新手。所以,我配置了属性文件并编写了示例程序来测试它。下面是我的配置文件和测试类。
< ?xml version="1.0" encoding="UTF-8" ?>
<!--<span class="hiddenSpellError" pre=""-->DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
-5p %c %x - %m%n"/>
</layout>
</appender>
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="./logs/testlog.log"/>
<layout class="org.apache.log4j.PatternLayout">
-5p %c %p - %m%n"/>
</layout>
</appender>
<root>
<priority value ="trace"></priority>
<appender-ref ref="console"></appender>
<appender-ref ref="fileAppender"></appender>
</root>
</log4j:configuration>
和样本测试类是
public class Log4jExample {
private static Logger logger=Logger.getLogger("Project_name");
public static void main(String[] args){
try{
FileInputStream fstream =
new FileInputStream("D:\\textfile.txt");
// use DataInputStream to read binary NOT text
// DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null){
System.out.println (strLine);
}
in.close();
}catch (FileNotFoundException fe){
logger.error("File Not Found",fe);
logger.warn("This is a warning message");
logger.trace("This message will not be logged since log level is set as DEBUG");
}catch (IOException e){
logger.error("IOEXception occured:", e);
}
}
}
我在netbeans工作,它显示logger.error,logger.trace,logger.warn是&#34;无法文件符号&#34;错误。请就此问题提出建议。
答案 0 :(得分:0)
确保您的类路径中有Log4j并且您的代码已编译。还要确保配置文件正确无误。您发布的文件是无效的xml。请查看Log4j xml format文档。这是语法修正版本:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="-5p %c %x - %m%n"/>
</layout>
</appender>
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="./logs/testlog.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="-5p %c %p - %m%n"/>
</layout>
</appender>
<root>
<priority value="trace"/>
<appender-ref ref="console"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>