⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timesizerollingfileappender.java

📁 《JSP网站开发典型模块与实例精讲》一书光盘源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.appfuse.util.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;

public class TimeSizeRollingFileAppender
    extends FileAppender
    implements
    ErrorCode {

    /**
     The default maximum file size is 10MB.
     */
    protected long maxFileSize = 10 * 1024 * 1024;

    /**
     There is one backup file by default.
     */
    protected int maxBackupIndex = 1;

    // The code assumes that the following constants are in a increasing
    // sequence.
    static final int TOP_OF_TROUBLE = -1;

    static final int TOP_OF_MINUTE = 0;

    static final int TOP_OF_HOUR = 1;

    static final int HALF_DAY = 2;

    static final int TOP_OF_DAY = 3;

    static final int TOP_OF_WEEK = 4;

    static final int TOP_OF_MONTH = 5;

    /**
     The date pattern. By default, the pattern is set to
     "'.'yyyy-MM-dd" meaning daily rollover.
     */
    private String datePattern = "'.'yyyy-MM-dd";

    /**
     The log file will be renamed to the value of the
     scheduledFilename variable when the next interval is entered. For
     example, if the rollover period is one hour, the log file will be
     renamed to the value of "scheduledFilename" at the beginning of
     the next hour.
     The precise time when a rollover occurs depends on logging
     activity.
     */
    private String scheduledFilename;

    /**
     The next time we estimate a rollover should occur. */
    private long nextCheck = System.currentTimeMillis() - 1;

    Date now = new Date();

    SimpleDateFormat sdf;

    RollingCalendar rc = new RollingCalendar();

    int checkPeriod = TOP_OF_TROUBLE;

    // The gmtTimeZone is used only in computeCheckPeriod() method.
    static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    /**
     *
     */
    private File currFile;

    /**
     The default constructor does nothing. */
    public TimeSizeRollingFileAppender() {

    }

    /**
     Instantiate a <code>TimeSizeRollingFileAppender</code> and open the
     file designated by <code>filename</code>. The opened filename will
     become the ouput destination for this appender.
     * @param filename
     * @param datePattern
     * @param layout
     * @throws java.io.IOException
     */
    public TimeSizeRollingFileAppender(Layout layout, String filename,
                                       String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    /**
     The <b>DatePattern</b> takes a string in the same format as
     expected by {@link SimpleDateFormat}. This options determines the
     rollover schedule.
     * @param pattern
     */
    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    /**
     * Returns the value of the <b>DatePattern</b> option.
     * @return String
     */
    public String getDatePattern() {
        return datePattern;
    }

    /**
     Returns the value of the <b>MaxBackupIndex</b> option.
     * @return int
     */
    public int getMaxBackupIndex() {
        return maxBackupIndex;
    }

    /**
     Get the maximum size that the output file is allowed to reach
     before being rolled over to backup files.
     * @return long
     @since 1.1
     */
    public long getMaximumFileSize() {
        return maxFileSize;
    }

    /**
     * @see org.apache.log4j.FileAppender#setFile(java.lang.String)
     */
    public void setFile(String file) {
        String FILE_SEP = System.getProperty("file.separator");
        // Trim spaces from both ends. The users probably does not want
        // trailing spaces in file names.
        String val = file.trim();
        String tmpfileName = val.replace('/', FILE_SEP.charAt(0));
        if (!tmpfileName.startsWith(FILE_SEP)) {
            tmpfileName = FILE_SEP + tmpfileName;
        }
        String rootPath = "";
        java.io.File curFile = new java.io.File(".");
        try {
            rootPath = curFile.getCanonicalPath();
        }
        catch (IOException ex) {
            System.err.println("Get app root path error:" +
                               ex.getMessage());
        }
        fileName = rootPath + tmpfileName;
        //create non-exist path
        LogLog.debug("fileName:" + fileName);

        int index = fileName.lastIndexOf(FILE_SEP);
        if (index > 0) {
            String sPath = fileName.substring(0, index);
            File path = new File(sPath);
            if (!path.exists()) {
                path.mkdirs();
            }
        }

        LogLog.debug("File set:" + fileName);
    }

    /**
     * @see org.apache.log4j.FileAppender#setFile(java.lang.String, boolean, boolean, int)
     */
    public synchronized void setFile(String pFileName, boolean append,
                                     boolean bufferedIO, int bufferSize) throws
        IOException {
        try {
            reset();
            this.fileName = pFileName;
            LogLog.debug("setFile called: " + fileName + ", " + append);
            // It does not make sense to have immediate flush and bufferedIO.
            if (bufferedIO) {
                setImmediateFlush(false);
            }

            Writer fw = createWriter(new FileOutputStream(fileName, append));
            if (bufferedIO) {
                fw = new BufferedWriter(fw, bufferSize);
            }
            this.setQWForFiles(fw);
            this.fileAppend = append;
            this.bufferedIO = bufferedIO;
            this.bufferSize = bufferSize;
            writeHeader();

            if (append) {
                currFile = new File(fileName);
                ( (CountingQuietWriter) qw).setCount(currFile.length());
            }
            LogLog.debug("setFile ended");
        }
        catch (IOException e) {
            //@CheckItem@ SELFBUG-yanfeng-20030716 创建日志文件失败,可能是权限不够
            errorHandler.error("Create log File error", e, FILE_OPEN_FAILURE);
        }
    }

    /**
     * @see org.apache.log4j.spi.OptionHandler#activateOptions()
     */
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            currFile = new File(fileName);
            scheduledFilename = fileName
                + sdf.format(new Date(currFile.lastModified()));
            LogLog.debug("scheduledFilename generated:" + scheduledFilename);
        }
        else {
            LogLog
                .error(
                "Either File or DatePattern options are not set for appender ["
                + name + "].");
        }
    }

    /**
     Set the maximum number of backup files to keep around.
     <p>The <b>MaxBackupIndex</b> option determines how many backup
     files are kept before the oldest is erased. This option takes
     a positive integer value. If set to zero, then there will be no
     backup files and the log file will be truncated when it reaches
     <code>MaxFileSize</code>.
     * @param maxBackups
     */
    public void setMaxBackupIndex(int maxBackups) {
        this.maxBackupIndex = maxBackups;
    }

    /**
     Set the maximum size that the output file is allowed to reach
     before being rolled over to backup files.
     <p>In configuration files, the <b>MaxFileSize</b> option takes an
     long integer in the range 0 - 2^63. You can specify the value
     with the suffixes "KB", "MB" or "GB" so that the integer is
     interpreted being expressed respectively in kilobytes, megabytes
     or gigabytes. For example, the value "10KB" will be interpreted
     as 10240.
     * @param value
     */
    public void setMaxFileSize(String value) {
        maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1);
        //maxFileSize=value;
    }

    /**
     * @param value
     */
    public void setMaximumFileSize(long value) {
        //maxFileSize=OptionConverter.toFileSize(value,maxFileSize+1);
        maxFileSize = value;
    }

    /**
     * @see org.apache.log4j.FileAppender#setQWForFiles(java.io.Writer)
     */
    protected void setQWForFiles(Writer writer) {
        this.qw = new CountingQuietWriter(writer, errorHandler);
    }

    void printPeriodicity(int type) {
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug("Appender [" + name
                             + "] to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug("Appender [" + name
                             + "] to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug("Appender [" + name
                             + "] to be rolled at midday and midnight.");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -