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

I want to create a log file for a query in the following format using java util logging.

YYYYMMDD_HHMMSS.log 

Someone please let me know how I can achieve this using the Java usage log.

0
source share
1 answer

FileHandler does not support creating file names using date and time from LogManager.

If you want to generate a file name at startup, you can subclass FileHandler and create a static method to generate your file name using SimpleDateFormat . LogManager supports the 'config' option, which also allows you to set your own code for installing and installing 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 for each LogRecord, you must create a custom Handler that will create and close the FileHandler on each of them published.

 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())); } } 
+1
source

All Articles