2013年10月27日 星期日

Log4j概念 與使用情境

那天在跟公司新人介紹log4j的時候

就突然想到其實這個設計很簡單啊 怎麼會一直都沒有被弄清楚?

所以 來吧!! 介紹一下!!

在log4j的官方文件上面有一段清楚地說明

http://logging.apache.org/log4j/1.2/manual.html

Log4j has three main components: loggersappenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.
Logger用來記錄訊息,包含log等級與log類型

Appender用來控制訊息會被放到什麼地方

Layout用來控制訊息的格式



簡單的情境如下

我們設定一個appender與layout

指定log會被記錄到檔案中 (appender)

並且會使用 "yyyy/mm/dd hh:MM:ss [訊息等級] 訊息內容" 格式來記錄訊息

接著設定 logger

指定一個logger要log的等級是INFO以上

並且將logger與appender接上


之後在程式裡面就取得此logger,並且使用應該使用的log等級來記錄訊息

例如
logger.trace("測試測試");
logger.debug("變數A = " + A);
logger.error("db conn. setting error.");


因為設定已經將log的等級設定為INFO

所以依照 TRACE < DEBUG < INFO < WARN < ERROR < FATAL 的等級

之前的訊息只有 error的項目 會被記錄到最後產生出來的檔案中