FileDailyRotateHandler.java 1.83 KB
/*
 * Decompiled with CFR 0_118.
 */
package com.scene7.is.ps.provider.logging;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;

public class FileDailyRotateHandler
extends StreamHandler {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private String pattern;
    private String filename;

    public FileDailyRotateHandler(String pattern) throws IOException {
        this.pattern = pattern;
        this.filename = this.genFilename(pattern);
        this.open(this.filename);
    }

    @Override
    public synchronized void publish(LogRecord record) {
        if (!this.isLoggable(record)) {
            return;
        }
        String newFilename = this.genFilename(this.pattern);
        if (!newFilename.equals(this.filename)) {
            this.rotate();
        }
        super.publish(record);
        this.flush();
    }

    private String genFilename(String pattern) {
        return pattern.replaceAll("%g", this.dateFormat.format(new Date()));
    }

    private void open(String fname) throws IOException {
        FileOutputStream fout = new FileOutputStream(fname, true);
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        this.setOutputStream(bout);
    }

    private void rotate() {
        Level oldLevel = this.getLevel();
        this.setLevel(Level.OFF);
        super.close();
        this.filename = this.genFilename(this.pattern);
        try {
            this.open(this.filename);
        }
        catch (IOException ex) {
            this.reportError(null, ex, 5);
            return;
        }
        this.setLevel(oldLevel);
    }
}