3

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?

Nathan
  • 8,093
  • 8
  • 50
  • 76
Raghvendra
  • 101
  • 1
  • 2
  • 5

1 Answers1

4

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;
}
}
Community
  • 1
  • 1
Panu
  • 362
  • 3
  • 13
  • Thanks for quick response But is their any other way to get extract logs from memory before server getting crash/restart? – Raghvendra Jun 17 '13 at 06:07
  • 1
    It depends how the server crashes. If the JVM crashes then there is very little one can do (full memory dump of the process should contain the buffer somewhere). If some exception causes JVM to exit then adding shutdown hook that flushes the log buffer might do the trick (see http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread). For flushing log4j buffers there seems to be already an answer (http://stackoverflow.com/a/3187802/647701). – Panu Jun 17 '13 at 06:12