Reputation: 115
I am using bufferedIO=true and bufferSize=8KB in log4j.properties, but suppose server get crashed/restrted due to some reason and buffer is not full then the logs in buffer will get lost. So how to recover those logs?
Upvotes: 3
Views: 6460
Reputation: 362
If the JVM crashes they cannot be recovered. They are buffered in memory and that memory is basically gone when the program crashes.
If the JVM just exits for some reason one could use shutdown hook. LogManager.shutdown() will flush logs (https://stackoverflow.com/a/3078377/647701). So it is enough just to add it as a shutdown hook.
/**
* Demonstrating how to flush buffered log4j logs to file when virtual machine exits.
*
*/
public class Log4JBufferWriterOnJVMExit {
public static void main(String[] args) throws IOException {
Logger log = initializeSomeLogToTestTheFlushing();
log.info("Here");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LogManager.shutdown();
}
});
}
private static Logger initializeSomeLogToTestTheFlushing() throws IOException {
FileAppender fileAppender = new FileAppender(new SimpleLayout(), "buffered.log", false, true, 8 * 1204);
Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(fileAppender);
Logger log = Logger.getLogger(Log4JBufferWriterOnJVMExit.class);
return log;
}
}
Upvotes: 4