导入log4j-1.2.12.jar,java代码如下:
- import org.apache.log4j.Logger;
- import org.apache.log4j.xml.DOMConfigurator;
- public class MainTest {
- private static Logger logger=Logger.getLogger(MainTest.class);
- public void test(){
- logger.debug("debug message");
- logger.info("info message");
- logger.warn("warn message");
- logger.error("error message");
- logger.fatal("fatal message");
- }
- public static void main(String args[]){
- DOMConfigurator.configure("log4j.xml");
- MainTest maintest = new MainTest();
- maintest.test();
- }
- }
xml配置文件:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
- <log4j:configuration>
- <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %5p [%-8c{1}] %m%n"/>
- </layout>
- </appender>
- <category name="MainTest" additivity="false">
- <priority value="info" />
- <appender-ref ref="stdout" />
- </category>
- </log4j:configuration>
输出结果:
12:52:51,289 INFO [MainTest] info message
12:52:51,289 WARN [MainTest] warn message
12:52:51,289 ERROR [MainTest] error message
12:52:51,289 FATAL [MainTest] fatal message