Log4j輸出到指定日誌檔案

weixin_34344677發表於2012-11-29

1、Log4j的概念

Log4j中有三個主要的元件,它們分別是 Logger、Appender和Layout,Log4j 允許開發人員定義多個Logger,每個Logger擁有自己的名字,Logger之間通過名字來表明隸屬關係。有一個Logger稱為Root,它永遠 存在,且不能通過名字檢索或引用,可以通過Logger.getRootLogger()方法獲得,其它Logger通過 Logger.getLogger(String name)方法。
Appender則是用來指明將所有的log資訊存放到什麼地方,Log4j中支援多種appender,如 console、files、GUI components、NT Event Loggers等,一個Logger可以擁有多個Appender,也就是你既可以將Log資訊輸出到螢幕,同時儲存到一個檔案中。
Layout的作用是控制Log資訊的輸出方式,也就是格式化輸出的資訊。
Log4j中將要輸出的Log資訊定義了5種級別,依次為DEBUG、INFO、WARN、ERROR和FATAL,當輸出時,只有級別高過配置中規定的級別的資訊才能真正的輸出,這樣就很方便的來配置不同情況下要輸出的內容,而不需要更改程式碼,這點實在是方便啊。

2、Log4j的配置檔案

package dxz.log4j;

import org.apache.log4j.Logger;

public class MultiLogger {

/** * @param args */

public static void main(String[] args) {

  // TODO Auto-generated method stub

  /** * 此外可以指定用哪個日誌,duan或者zhang */

  Logger log = Logger.getLogger("DBUpgrade");

  for(int i=0;i<10;i++){

    log.debug("DBUpgrade");

    log.info("DBUpgrade");

    log.warn("DBUpgrade");

    log.error("DBUpgrade");

  }

  Logger log2 = Logger.getLogger("zhang");

  for(int i=0;i<10;i++){

    log2.debug("zhang");

    log2.info("zhang");

    log2.warn("zhang");

    log2.error("zhang");

  }

  }

}

 

####log4j.properties###################

log4j.logger.duan=DEBUG,A

log4j.appender.A=org.apache.log4j.DailyRollingFileAppender

log4j.appender.A.File=E:/test/log/duan.log

log4j.appender.A.layout=org.apache.log4j.PatternLayout

log4j.appender.A.layout.ConversionPattern=%d%m%n

log4j.logger.zhang=DEBUG,C log4j.appender.B=org.apache.log4j.ConsoleAppender

log4j.appender.B.layout=org.apache.log4j.PatternLayout

log4j.appender.B.layout.ConversionPattern=%l%d%m%n

log4j.appender.C=org.apache.log4j.DailyRollingFileAppender

log4j.appender.C.File=E:/test/log/zhang.log

log4j.appender.C.layout=org.apache.log4j.PatternLayout

log4j.appender.C.layout.ConversionPattern=%d%m%n

log4j.logger.DBUpgrade=DEBUG,DBUpgrade

# Rolling file appender

log4j.appender.DBUpgrade=org.apache.log4j.RollingFileAppender

log4j.appender.DBUpgrade.File=e:/test/log/DBUpgradeLog.log

log4j.appender.DBUpgrade.MaxFileSize=100KB

log4j.appender.DBUpgrade.MaxBackupIndex=2

log4j.appender.DBUpgrade.layout=org.apache.log4j.PatternLayout

log4j.appender.DBUpgrade.layout.ConversionPattern=%d{MMM dd, yyyy hh:mm:ss a} %-5p [%c{1}] %m%n

log4j.appender.DBUpgrade.threshold=DEBUG

結果:

DBUpgradeLog.log

十一月 29, 2012 04:44:25 下午 DEBUG [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 INFO [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 WARN [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 ERROR [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 DEBUG [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 INFO [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 WARN [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 ERROR [DBUpgrade] DBUpgrade

十一月 29, 2012 04:44:25 下午 DEBUG [DBUpgrade] DBUpgrade

duan.log

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,369duan

2012-11-29 16:28:57,370duan

2012-11-29 16:28:57,370duan

 

不如寫一個能夠實現以上功能的類吧。

MultiFileLoggerByLogLevel.java

package com.bjinfotech.practice.logging;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Category;
import org.apache.log4j.FileAppender;
/**
* 使用isEnableFor方法作判斷,提高了log的效能,避免了處理低等級的資訊導致的系統浪費
* 根據日誌level建立多個不同級別的log,將日誌內容按照級別寫入不同的日誌檔案
*
*/
public class MultiFileLoggerByLogLevel {
        public static final int DEBUG=0;
        public static final int INFO=1;
        public static final int WARN=2;
        public static final int ERROR=3;
        public static final int CATEGORY_MAXNUM=4;
        
        private String[] categoryNameArray={"DEBUG","INFO","WARN","ERROR"};
        private Category[] categoryArray=new Category[CATEGORY_MAXNUM];
        
        /**
         * 構造方法
         * @param propertyFilePath 配置檔案路徑
         */
        public MultiFileLoggerByLogLevel(String propertyFilePath){
                init(propertyFilePath);
        }
        
        /**
         * 初始化,建立category陣列
         * @param propertyFilePath 配置檔案路徑
         */
        private void init(String propertyFilePath ){
                PropertyConfigurator.configure(propertyFilePath);
                for(int i=0;i<CATEGORY_MAXNUM;i++){
                        categoryArray[i]=Category.getInstance(categoryNameArray[i]);
                        FileAppender fileAppender=(FileAppender)categoryArray[i].getAppender("R_"+categoryNameArray[i]);
                        categoryArray[i].addAppender(fileAppender);
                }
        }
        
        public void debug(String msg){
                if (categoryArray[DEBUG].isEnabledFor(Level.DEBUG)){
                        categoryArray[DEBUG].debug(msg);
                }
        }
        
        public void info(String msg){
                if (categoryArray[INFO].isEnabledFor(Level.INFO)){
                        categoryArray[INFO].info(msg);
                }
        }
        
        public void warn(String msg){
                if (categoryArray[WARN].isEnabledFor(Level.WARN)){
                        categoryArray[WARN].warn(msg);
                }
        }
        
        public void error(String msg){
                if (categoryArray[ERROR].isEnabledFor(Level.ERROR)){
                        categoryArray[ERROR].error(msg);
                }
        }
        
        public static void main(String[] args) {
                String propertyFilePath="./src/com/bjinfotech/practice/logging/multiFileLoggerConfig.properties";
                MultiFileLoggerByLogLevel mflogger=new MultiFileLoggerByLogLevel(propertyFilePath);
                mflogger.debug("test");
                mflogger.info("test");
                mflogger.warn("test");
                mflogger.error("test");
        }
}

log4j的屬性檔案如下:
multiFileLoggerConfig.properties

log4j.rootCategory=DEBUG,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.category.ERROR=ERROR,stdout,R_ERROR
log4j.additivity.ERROR=false

log4j.appender.R_ERROR=org.apache.log4j.RollingFileAppender
log4j.appender.R_ERROR.file=example_ERROR.log
log4j.appender.R_ERROR.MaxFileSize=100KB
log4j.appender.R_ERROR.MaxBackupIndex=1
log4j.appender.R_ERROR.layout=org.apache.log4j.PatternLayout
log4j.appender.R_ERROR.layout.ConversionPattern=%p %t %c - %m%n

log4j.category.WARN=WARN,stdout,R_WARN
log4j.additivity.WARN=false

log4j.appender.R_WARN=org.apache.log4j.RollingFileAppender
log4j.appender.R_WARN.file=example_WARN.log
log4j.appender.R_WARN.MaxFileSize=100KB
log4j.appender.R_WARN.MaxBackupIndex=1
log4j.appender.R_WARN.layout=org.apache.log4j.PatternLayout
log4j.appender.R_WARN.layout.ConversionPattern=%p %t %c - %m%n

log4j.category.INFO=INFO,stdout,R_INFO
log4j.additivity.INFO=false

log4j.appender.R_INFO=org.apache.log4j.RollingFileAppender
log4j.appender.R_INFO.File=example_INFO.log
log4j.appender.R_INFO.MaxFileSize=100KB
log4j.appender.R_INFO.MaxBackupIndex=1
log4j.appender.R_INFO.layout=org.apache.log4j.PatternLayout
log4j.appender.R_INFO.layout.ConversionPattern=%p %t %c - %m%n

log4j.category.DEBUG=DEBUG,stdout,R_DEBUG
log4j.additivity.DEBUG=false

log4j.appender.R_DEBUG=org.apache.log4j.RollingFileAppender
log4j.appender.R_DEBUG.File=example_DEBUG.log
log4j.appender.R_DEBUG.MaxFileSize=100KB
log4j.appender.R_DEBUG.MaxBackupIndex=1
log4j.appender.R_DEBUG.layout=org.apache.log4j.PatternLayout
log4j.appender.R_DEBUG.layout.ConversionPattern=%p %t %c - %m%n

相關文章