/**
* This method updated the passed in java.util.logging.Logger object with
* custom file handler to write logs data form that class in separate file.
*
* 1. New log file name patter is NewLogFile_%g.log where %g is sequential number starting with 0
* 2. New Log file size max limit is 25MB after that system will rotate log in new file where %g is replaced by next sequence
* 3. From log request/response message all new line, space and tabs characters are removed
* 4. To enable/disable logging we still use OOB WAS admin console Logs & Trace configuration
* 5. To enable logging for a class in separate file add log level as "com.xyz.XYZClassName=fine"
* in WAS admin console Logs & Trace configuration
* 6. To disable logging remove above log level from logs configuration in WAS admin console
* 7. Max number of new log files count is 20 as passed in new FileHandler argument
* 8. String.format("[%1$tF %1$tT %1$tZ] ",new Date(record.getMillis())) will format date as [2021-10-01 15:24:26 BST]
*
* @param logger java.util.logging.Logger lass object obtained like Logger.getLogger(CLASSNAME)
* @param newLogFile: newLogFile = System.getenv("USER_INSTALL_ROOT")+"\\logs\\server1\\NewLogFile_%g.log"
*/
public static void updateLoggerWithCustomHandler(Logger logger,String newLogFile) {
try {
Handler fileHandler = new FileHandler(newLogFile, 25000000, 20,true);
fileHandler.setFormatter(new SimpleFormatter() {
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("[%1$tF %1$tT %1$tZ] ",new Date(record.getMillis())));
sb.append(String.format("%1$08x",record.getThreadID())).append(" ");
sb.append(record.getSourceClassName()).append(" ");
sb.append(record.getSourceMethodName()).append(" ");
sb.append(record.getMessage().replaceAll("[\\n\\t\\s]", ""));
sb.append(System.getProperty("line.separator"));
if (null != record.getThrown()) {
sb.append("Throwable occurred: ");
Throwable thrown = record.getThrown();
PrintWriter printWriter = null;
try {
StringWriter stringWriter = new StringWriter();
printWriter = new PrintWriter(stringWriter);
thrown.printStackTrace(printWriter);
sb.append(stringWriter.toString());
} finally {
if (printWriter != null) {
try {
printWriter.close();
} catch (Exception e) {
// ignore
}
}
}
}
return sb.toString();
}
});
logger.setUseParentHandlers(false);
logger.addHandler(fileHandler);
} catch (IOException e) {
//Error while creating separate log file for OS api logging
}
}
NOTE: call above defined static method updateLoggerWithCustomHandler static block on class which requires logger update and logger object should be fetched as public static class level instance variable like Logger LOGGER = Logger.getLogger(CLASSNAME);