Java-Seekar Java-Seekar - 4 months ago 9
Java Question

How to create the log file for each record in a specific format using java util logging framework

I want to create the log file per request in the format below, using java util logging.

YYYYMMDD_HHMMSS.log


Anybody please let me know how can I achieve this using java util logging?

Answer

The FileHandler doesn't support generating file names by date and time from the LogManager.

If you want to generate a file name on startup you can subclass the FileHandler and create a static method to generate your file name using a SimpleDateFormat. The LogManager supports a 'config' option that will also allow you to install custom code to setup and install a FileHandler.

public class RollingFileHandler extends FileHandler {

    public RollingFileHandler() throws IOException {
        super(fileName(), 0, 1, true);
    }

    private static String fileName() {
        return new SimpleDateFormat("'%h'yyyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
    }
}

If you want to generate a file name per each LogRecord you have to create a custom Handler that will create and close a FileHandler on each publish.

public class DatedFileHandler extends Handler {

    @Override
    public synchronized void publish(LogRecord r) {
        if (isLoggable(r)) {
            try {
                FileHandler h = new FileHandler(fileName(r), 0, 1, true);
                try {
                    h.setLevel(getLevel());
                    h.setEncoding(getEncoding());
                    h.setFilter(getFilter());
                    h.setFormatter(getFormatter());
                    h.setErrorManager(getErrorManager());
                    h.publish(r);
                } finally {
                    h.close();
                }
            } catch (IOException | SecurityException jm) {
                this.reportError(null, jm, ErrorManager.WRITE_FAILURE);
            }
        }
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
        super.setLevel(Level.OFF);
    }

    private String fileName(LogRecord r) {
        return new SimpleDateFormat("'%h'yyyyMMdd_HHmmss").format(new Date(r.getMillis()));
    }
}
Comments