---
title: "Log4j 学习笔记之一"
author: "sammor"
date: "2010-11-15T11:17:40Z"
tags: ["Apache", "HTML", "XML", "log4j", "maven"]
categories: ["企业架构"]
slug: "log4j"
draft: false
lastmod: "2010-11-15T12:23:25Z"
id: 811560
url: "https://sammor.iteye.com/blog/811560"
---

**引言：**

       这两天在学习日志处理，告别System.out.println();的时代。

System.out.println()对于很多还不怎么接触项目的童鞋来说，是一样再正常不过的查看运行状态的一个用法了。

但这毕竟是一时的，在真正的项目运用中，这个方式是不提倡使用的。

 

**一、System.out.println()给程序带来了什么问题**

       1、程序过多的System.out.println()给程序代码带来了很多杂乱的代码

       2、System.out.println()的作用只能输出显示在控制台上，是临时性的，无法将这些日志保存在文件中

       3、人为的干涉System.out.println()，当不要求显示出这些信息的时候，要求人为的去找出这些代码的位置并注释（麻烦）

       4、System.out.println()并不能分级的显示信息，有些是提示，有些是错误等等，System.out.println()只会全盘的托出。

 

**二、Log4j带来的好处**

1. Log4j代码清晰，可以清楚的去定义是提示信息，还是错误信息，还是调试信息，等等。（下面会讲到7种信息提示级别）
2. Log4j通过log4j.properties的配置文件，可以配置不同的输出方式，有（控制台、文件、html、mail等方式）可以选择
3. Log4j也可以通过配置文件可以设置，需要显示哪些层级的信息，灵活性更高。

三、Log4j 的 Quick Start

- 需要的jar包

          http://logging.apache.org/log4j/1.2/download.html中下载jar包

 

          ps: 如何是maven工程的话，可以在Pom.xml中加入以下代码

 

```
<dependency>
	<groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
             <version>1.2.14</version>
		<type>jar</type>
             <scope>compile</scope>
</dependency>
```

 

- 写测试类名为TestLog4j。

 

```
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class TestLog4j {

	//创建一个私有的日志对象
	private Logger log = Logger.getLogger(TestLog4j.class);
	
	public void execute(){
		//加载配置文件，很重要。
		PropertyConfigurator.configure("D:\\log4j.properties");
		
		//写出需要显示的信息
		log.debug("Just testing a log message with priority set to DEBUG");
		log.info("Just testing a log message with priority set to INFO");
		log.warn("Just testing a log message with priority set to WARN");
		log.error("Just testing a log message with priority set to ERROR");
		log.fatal("Just testing a log message with priority set to FATAL");

	}
	
	public static void main(String[] args) {
		TestLog4j log4j = new TestLog4j();
		log4j.execute();
	}
}
```

 

    这里面有写着我的配置文件的地址

    配置文件内容：

 

```
#print to console
log4j.rootLogger = debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t](%r %x  %c) (%F:%L) - %m%n
```

 

    运行下，执行的结果为：

 

```
DEBUG [main](0   TestLog4j) (TestLog4j.java:15) - Just testing a log message with priority set to DEBUG
 INFO [main](0   TestLog4j) (TestLog4j.java:16) - Just testing a log message with priority set to INFO
 WARN [main](0   TestLog4j) (TestLog4j.java:17) - Just testing a log message with priority set to WARN
ERROR [main](0   TestLog4j) (TestLog4j.java:18) - Just testing a log message with priority set to ERROR
FATAL [main](0   TestLog4j) (TestLog4j.java:19) - Just testing a log message with priority set to FATAL
```

    这就是一个大致的流程了，当然这里面还有很多需要学习的地方。下面就是对Log4j整体的一个学习吧。

 

END