Java日誌服務入門系列教程——(2)Apache log4j入門

鍾超發表於2011-12-15

1. 概述

目前log4j有三個發展分支,一個是1.2的穩定版,一個是已經停止繼續發展的1.3版本,另一個就是實驗階段的2.0版本。Apache log4j官網上稱,在一臺載有執行在800MHz的AMD Duron CPU並使用JDK 1.3.1 上的計算機中,log4j 1.2 只需要5納秒就可以完成一個日誌語句是應該作為日誌輸出還是不輸出的決定。


2. 下載log4j 1.2 API library

從人人網的實驗室下載:

http://labs.renren.com/apache-mirror//logging/log4j/1.2.16/apache-log4j-1.2.16.zip

從BJTU下載:

http://mirror.bjtu.edu.cn/apache//logging/log4j/1.2.16/apache-log4j-1.2.16.zip


3. log4j的Hello World 程式原始碼

package com.sinosuperman.log4j;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Test {
	private static final Logger logger = Logger.getLogger(Test.class);
	public static void main(String[] args) {
		BasicConfigurator.configure();
		logger.info("Hello World, This is an information message.");
		logger.error("Hello World, This is a error message.");
		logger.warn("Hello World, This is a warning message.");
		logger.debug("Hello World, This is a debugging message.");
		logger.fatal("Hello World, This is a fatal message.");
		System.exit(0);
	}
}

4. log4j的Hello World 程式執行結果

1 [main] INFO com.sinosuperman.log4j.Test  - Hello World, This is an information message.
3 [main] ERROR com.sinosuperman.log4j.Test  - Hello World, This is a error message.
3 [main] WARN com.sinosuperman.log4j.Test  - Hello World, This is a warning message.
3 [main] DEBUG com.sinosuperman.log4j.Test  - Hello World, This is a debugging message.
3 [main] FATAL com.sinosuperman.log4j.Test  - Hello World, This is a fatal message.


相關文章