log4j項目中隨處可見的一個工具包,小但卻很重要,老樣子,執行個體驅動。
1、匯入包:
log4j-1.2.14.jar
junit.jar
org.hamcrest.core_1.1.0.v20090501071000.jar
2、日誌類
public class UserDao {// 建立Logger對象public static final Logger logger = Logger.getLogger(UserDao.class);public void add() {/** * 可以為日誌設定不同的層級,在log4j中 debug<info<warn<error<fatal */logger.debug("添加了使用者資訊");logger.info("添加了使用者資訊");logger.warn("添加了使用者資訊");logger.error("添加了使用者資訊");logger.fatal("添加了使用者資訊");}}
3、編寫日誌設定檔
#kong zhi tai shu chulog4j.appender.stout=org.apache.log4j.ConsoleAppenderlog4j.appender.stout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stout.layout.ConversionPattern=[%p](%l)-->%m(%d)%nlog4j.rootLogger=DEBUG,stoutlog4j.logger.org.tgb.log4j.dao =DEBUG,stout
PS:stout是控制台輸出的日誌格式,如果想組建記錄檔檔案txt格式的,需要改成fout(這是後話,後面的部落格會實現的)
stout:控制台輸出的日誌格式
layout:日誌輸出布局格式
ConversionPattern:日誌輸出樣式
log4j的記錄層級是:debug<info<warn<error<fatal
log4j.rootLogger=DEBUG,stout,設定的Debug以上的記錄層級都會輸出。如果debug換成warn則只會顯示warn以上層級的日誌資訊 4、測試&效果
@Testpublic void testLog() {UserDao ud = new UserDao();ud.add();}
debug層級:
Warn層級:
這篇部落格只是自訂了log4j.property屬性檔案來簡單的實現了一下日誌輸出,下一篇將日誌資訊輸出到txt檔案夾中
(未完,待續)