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

1

1

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?

Declarer answered 10/12, 2013 at 6:54 Comment(2)
per which request? Do you have existing code we can see using logging?Jabalpur
I have a stand alone SE application. When I execute that application each time I want to create different log files according to the time format.Declarer
M
2

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()));
    }
}
Mcgrath answered 10/12, 2013 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.