如何在JVM退出时刷新log4j appender?

时间:2013-06-17 05:50:30

标签: log4j rollingfileappender

我在log4j.properties中使用bufferedIO = true和bufferSize = 8KB,但是假设服务器由于某种原因而崩溃/重新设置并且缓冲区未满,则缓冲区中的日志将丢失。那么如何恢复这些日志?

1 个答案:

答案 0 :(得分:4)

如果JVM崩溃,则无法恢复。它们被缓冲在内存中,当程序崩溃时内存基本消失。

如果JVM因某种原因退出,可以使用shutdown hook。 LogManager.shutdown()将刷新日志(https://stackoverflow.com/a/3078377/647701)。所以仅将它添加为关闭钩子就足够了。

/**
 * 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;
}
}