close

  上個月寫個Log4J以類別全名作為檔名的Log檔,每個類別都有自己的Log file。若還要再加個需求是Log File可以Daily Rolling,承襲上次的寫法也不困難:

public class DynaDailyRollingAppender extends DailyRollingFileAppender {
    private static String oldFileName = null;
    private static String oldPath = null;
    public void generateLogFile(LocationInfo info) {       
        if (oldPath == null) {
            oldPath = this.fileName.substring(0, this.fileName.lastIndexOf("test"));
        }
        SimpleDateFormat sdf = new SimpleDateFormat(this.getDatePattern());
        String fileName1 = oldPath;
        fileName1 += info.getClassName() + sdf.format(Calendar.getInstance().getTime());
        oldFileName = fileName1;
        this.setFile(fileName1);   
        this.activateOptions();
    }
    @Override
    protected void subAppend(LoggingEvent event) {
        String className =  event.getLocationInformation().getClassName();
        this.logger1.info("Class:" + className);
        if (oldFileName != className) {
            this.generateLogFile(event.getLocationInformation());
        }
        super.subAppend(event);
    }
}

  在log4j.properties若設成DailyRolling的話,會有這樣的屬性設定:

log4j.appender.dynadailyrolling.DatePattern='.'yyyy-MM-dd'.log'

  這樣就會在log file後面補上.2009-10-25.log(以今天為例),是故上述getDatePattern便是取得'.'yyyy-MM-dd'.log',再用java.text.SimpleDateFormat抓今天的日期進行format,就得到我們要的檔名。

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()