日志去哪了
把一个服务去掉 SpringBoot 依赖的时候,发现 shutdown hook 运行不正常了,有开始执行的日志,执行完成的却没有。
重现也很方便,新建一个 maven 工程,增加一个启动类,如下
@Slf4j
public class Application {
public static void main(String[] args) {
log.info("start application...");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
destroy();
} catch (InterruptedException e) {
log.error("stop working failed",e);
}
}));
}
public static void destroy() throws InterruptedException {
log.info("stop working...");
Thread.sleep(1000);
log.info("working stopped...");
}
}
log4j2 默认的日志输出级别是 error,需要调整为 info 。
运行结果
18:08:43.082 [main] INFO com.zworks.log4jshutdown.java.Application - start application...
18:08:43.085 [Thread-1] INFO com.zworks.log4jshutdown.java.Application - stop working...
Process finished with exit code 0
可以看到日志输出是没问题,但是 shutdown hook 运行结束的日志却没有输出,是程序提前退出了吗
这里可以进行 debug ,或者更简单的,在最后使用 System.out
进行输出,不管使用哪种方法,其实都可以证明程序执行完成,只是日志没有输出。
log4j2 shutdown hook
翻看 log4j2 的配置,可以发现,有一个 shutdownHook 的配置,默认是开启的
Specifies whether or not Log4j should automatically shutdown when the JVM shuts down. The shutdown hook is enabled by default but may be disabled by setting this attribute to “disable”
如果开启,则会注册一个 shutdown hook &#