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,来指定接收日志信息的时间区间。
Log4j 2.0 使用说明的更多相关文章
- Log4j 2.0 使用说明(1) 之HelloWorld
以下是Log4j2.0的类图,以便大家对2.0有一个整体的理解. 就如我们学习任何一个技术一样,这里我们首先写一个Hello World: 1,新建工程TestLog4j 2,下载Log4j 2.0有 ...
- Log4j 2.0在开发中的高级使用具体解释—配置简单的控制台输出(三)
Log4j 2.0在近期迎来了重大的版本号升级.攻克了1.x中死锁bug之外,性能也有10倍的提升. 相同的在最新版本号中的新特性中. 配置文件也不只局限于xml和java特性文件properties ...
- Log4j 2.0在具体解释发展先进的使用—SocketAppender远程输出(五岁以下儿童)
Log4j2的Appenders充分考虑输出日志事件.包装和过滤可以被转发,它包含的主要输出到本地文件.输出到远程主机, 文件包.注射.而且,根据该日志文件的时间点.自己主动文件大小的储存条件. 例如 ...
- Log4j 2.0在开发中的高级使用具体解释—介绍篇(一)
Log4j最终迎来了首个apache版本号.Log4j 2 是 Log4j 的升级版本号,该版本号比起其前任来说有着显著的改进,包括非常多在 Logback 中的改进以及Logback 架构中存在的问 ...
- 中小研发团队架构实践之生产环境诊断工具WinDbg 三分钟学会.NET微服务之Polly 使用.Net Core+IView+Vue集成上传图片功能 Fiddler原理~知多少? ABP框架(asp.net core 2.X+Vue)模板项目学习之路(一) C#程序中设置全局代理(Global Proxy) WCF 4.0 使用说明 如何在IIS上发布,并能正常访问
中小研发团队架构实践之生产环境诊断工具WinDbg 生产环境偶尔会出现一些异常问题,WinDbg或GDB是解决此类问题的利器.调试工具WinDbg如同医生的听诊器,是系统生病时做问题诊断的逆向分析工具 ...
- SerialPort-4.0.+ 使用说明(Java版本)
SerialPort-4.0.+ 项目官网 Kotlin版本使用说明 介绍 SerialPort 是一个开源的对 Android 蓝牙串口通信的轻量封装库,轻松解决了构建自己的串口调试APP的复杂程度 ...
- SerialPort-4.0.+ 使用说明(Kotlin版本)
SerialPort-4.0.+ 项目官网 Java版本使用说明 介绍 SerialPort 是一个开源的对 Android 蓝牙串口通信的轻量封装库,轻松解决了构建自己的串口调试APP的复杂程度,让 ...
- WCF 4.0 使用说明
WCF 4.0开发说明,工具VS2013 ,IIS,使用http协议 打开VS2013,新建项目Visual C#>Web>Asp.NET Web应用程序,添加相关引用: System.S ...
- Gprinter Android SDK V1.0 使用说明
佳博打印机代理商淘宝店https://shop107172033.taobao.com/index.htm?spm=2013.1.w5002-9520741823.2.Sqz8Pf 在此店购买的打印机 ...
随机推荐
- iOS:实现表格填充和选择操作
功能:创建一个列表,用数组填充表格,并支持选择列表行 // // main.m // Hello // // Created by lishujun on 14-8-28. // Copyright ...
- strong ,weak
有时我们写个代码开源出来给别人用时,会被其他开发者抱怨编译不了,很多情况是版本的问题,尤其现在ARC的出现后关于weak,strong的问题让人头疼.有个开源代码这里做的很不错,就是MBProgres ...
- windows下端口被占用的解决方法
1:打开CMD输入:netstat -ano | findstr "80" 找到PID: 2:查看应用名称:tasklist | findstr "2544" ...
- Greg and Array
Codeforces Round #179 (Div. 2) C:http://codeforces.com/problemset/problem/296/C 题意:给你一个序列,然后有两种操作,第一 ...
- UIImageView之我的动画为什么停了?UIImageView, highLighted,animationImages
如果你的动画总是停了!停了!停了!不管你想不想都停,这里有个参考,你可以看看!这只是一种可能性!!! 受最近看到段子影响,画风略诡异,不喜勿喷. 最近在“刻”动画!!! 为什么是“刻”,动画写了3周啊 ...
- Delphi基本图像处理代码
//浮雕procedure Emboss(SrcBmp,DestBmp:TBitmap;AzimuthChange:integer);overload;var i, j, Gray, Azimuth ...
- 大型系统OA--需求
1.面向普通用户 普通用户一般都是公司的小职员,上OA都干什么呢?当然是获取信息咯.还有最好很多事儿,不需要跟公司的其他部门的人儿,打交道,直接在网上解决就好了. 收发邮件: 查看自己发动的流程,也就 ...
- SqlServer:CTE函数处理递归(WITH语法)
我们在做分类处理的时候,总会遇到递归的处理,比如说地区就是一个例子,中国--北京--西城区,我们可以把这样的信息存储在一个数据表中,用ParentID区分根节点和叶子节点.假如我们要做导航,得到了”西 ...
- OpenStack学习推荐
前言: 学习.了解.安装部署OpenStack也写了好一段时间了,现在觉得也有点必要写点总结.搞IT这一块基本就这样,不管是搞什么领域,一个项目超过两个月没动它,就基本不知道当时是怎么搞的,当时学 ...
- 《University Calculus》-chape8-无穷序列和无穷级数-欧拉恒等式
写在前面:写在前面的当然是对大天朝教材的吐槽啦. 曾记否,高中所学虚数和复平面的概念,如此虚无的概念到了大学一门叫<模拟电子技术>的课程中居然明目张胆的开始进行计算! 曾记否,高中的指对运 ...