Log4j 2.0 使用说明
原文地址:http://blog.csdn.net/welcome000yy/article/details/7962447
Log4j 2.0 使用说明(1) 之HelloWorld
最近刚接触Log4j,由于Log4j推出了2.0版本,而网上关于2.0的资料很少,所在在这里简要介绍下2.0版本的使用。
以下是2.0的类图,以便大家对2.0有一个整体的理解。
就如我们学习任何一个技术一样,这里我们首先写一个Hello World:
1,新建工程TestLog4j
2,下载Log4j 2.0有jar包,导入下面两个文件
3,编写代码:
[java]
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class HelloWorld { private static Logger logger = LogManager.getLogger("HelloWorld"); public static void main(String[] args) { logger.info("Hello, World!"); logger.error("Hello, World!"); } }
输出为:
11:11:15.343 [main] ERROR HelloWorld - Hello, World!
由输出我们可以看到程序只是打印出了error的信息,这是由于我们没提供配置文件,而缺省的配置文件默认的优先级是Error,故只打印了error的信息。
Log4j 2.0 使用说明(2) 配置文件
在这里我们试着添加配置文件。
另外,我们需要注意的是2.0版本中的配置只能为Xml和Json。
测试代码为:
[java]
package com.foo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Bar { static Logger logger = LogManager.getLogger(Bar.class.getName()); public boolean doIt() { logger.entry(); //Log entry to a method logger.error("Did it again!"); //Log a message object with the ERROR level logger.exit(); //Log exit from a method return false; } }
[java]
import com.foo.Bar; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MyApp { // Define a static logger variable so that it references the // Logger instance named "MyApp". private static Logger logger = LogManager.getLogger(MyApp.class.getName()); public static void main(String[] args) { // Set up a simple configuration that logs on the console. logger.trace("Entering application."); //Log a message object with the TRACE level. Bar bar = new Bar(); if (!bar.doIt()) { logger.error("Didn't do it."); } logger.trace("Exiting application.");
}
}
没有配置文件情况下的输出为:
17:13:01.540 [main] ERROR com.foo.Bar - Did it again!
17:13:01.540 [main] ERROR MyApp - Didn't do it.
由之前的例子我们不难知道,这是因为缺省配置文件的优先级默认为Error的缘故。
下面的配置文件在效果上等于缺省情况的下的配置文件:
[XML]
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> </appenders> <loggers> <root level="error"> <appender-ref ref="Console" /> </root> </loggers> </configuration>
输出结果为:
11:43:57.703 [main] TRACE edu.hrbeu.tested.MyApp - Entering application.
11:43:57.718 [main] TRACE com.foo.Bar - entry
11:43:57.718 [main] ERROR com.foo.Bar - Did it again!
11:43:57.718 [main] TRACE com.foo.Bar - exit
11:43:57.718 [main] ERROR edu.hrbeu.tested.MyApp - Didn't do it.
11:43:57.718 [main] TRACE edu.hrbeu.tested.MyApp - Exiting application.
将优先级设置为trace后就可以显式的跟踪程序的执行过程。
若是我们想去掉除com.foo.Bar以外所有的trace输出,我们可以增加一个新的注册事件,如下所示
[XML]
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> </appenders> <loggers> <logger name="com.foo.Bar" level="trace" additivity="false"> <appender-ref ref="Console" /> </logger> <root level="error"> <appender-ref ref="Console" /> </root> </loggers> </configuration>
11:53:31.796 [main] TRACE com.foo.Bar - entry
11:53:31.796 [main] ERROR com.foo.Bar - Did it again!
11:53:31.796 [main] TRACE com.foo.Bar - exit
11:53:31.796 [main] ERROR edu.hrbeu.tested.MyApp - Didn't do it.
Log4j 2.0 使用说明(3) 之组件及过滤器
测试用代码:
[java]
package com.test; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class TestService { private Logger logger = LogManager.getLogger(TestService.class.getName()); private String[] messages = new String[] { "Hello, World", "Goodbye Cruel World", "You had me at hello" }; private Random rand = new Random(1); public String retrieveMessage() { logger.entry(); String testMsg = getMessage(getKey()); return logger.exit(testMsg); } public void exampleException() { logger.entry(); try { String msg = messages[messages.length]; logger.error("An exception should have been throw"); } catch (Exception e) { logger.catching(e); } logger.exit(); } public String getMessage(int key) { logger.entry(key); String value = messages[key]; return logger.exit(value); } public int getKey() { logger.entry(); int key = rand.nextInt(messages.length); return logger.exit(key); } }
[java]
package com.test; public class App { public static void main(String[] args) { TestService service = new TestService(); service.retrieveMessage(); service.retrieveMessage(); service.exampleException(); } }
程序输出:
10:10:46.078 TRACE com.test.TestService 19 retrieveMessage - entry
10:10:46.171 TRACE com.test.TestService 42 getKey - entry
10:10:46.171 TRACE com.test.TestService 44 getKey - exit with (0)
10:10:46.171 TRACE com.test.TestService 36 getMessage - entry parms(0)
10:10:46.171 TRACE com.test.TestService 38 getMessage - exit with (Hello, World)
10:10:46.171 TRACE com.test.TestService 21 retrieveMessage - exit with (Hello, World)
10:10:46.171 TRACE com.test.TestService 19 retrieveMessage - entry
10:10:46.171 TRACE com.test.TestService 42 getKey - entry
10:10:46.171 TRACE com.test.TestService 44 getKey - exit with (1)
10:10:46.171 TRACE com.test.TestService 36 getMessage - entry parms(1)
10:10:46.171 TRACE com.test.TestService 38 getMessage - exit with (Goodbye Cruel World)
10:10:46.171 TRACE com.test.TestService 21 retrieveMessage - exit with (Goodbye Cruel World)
10:10:46.171 TRACE com.test.TestService 25 exampleException - entry
10:10:46.171 DEBUG com.test.TestService 30 exampleException - catching java.lang.ArrayIndexOutOfBoundsException: 3
at com.test.TestService.exampleException(TestService.java:27) [bin/:?]
at com.test.App.main(App.java:9) [bin/:?]
10:10:46.187 TRACE com.test.TestService 32 exampleException - exit
其Xml配置文件为:
[XML]
<?xml version="1.0" encoding="UTF-8"?> <configuration status="error"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" /> </Console> <File name="log" fileName="target/test.log" append="false"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" /> </File> <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"> <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n" /> <SizeBasedTriggeringPolicy size="500 MB" /> </RollingFile> </appenders> <loggers> <root level="trace"> <appender-ref ref="RollingFile" /> <appender-ref ref="Console" /> </root> </loggers> </configuration>
1,ConsoleAppender
输出结果到System.out或是System.err。
2,FileAppender
输出结果到指定文件,同时可以指定输出数据的格式。
3,RollingFileAppender
自动追加日志信息到文件中,直至文件达到预定的大小,然后自动重新生成另外一个文件来记录之后的日志。
过滤标签
1,ThresholdFilter
用来过滤指定优先级的事件。
2,TimeFilter
设置start和end,来指定接收日志信息的时间区间。