我正在尝试在基于Tomcat的Web应用程序中使用log4j2,因此我添加了log4j web模块以及其他必要的jar包。但是当停止这个Web应用程序时,我会遇到以下异常。
FATAL Unable to register shutdown hook because JVM is shutting down
为什么会出现这个错误,我该如何避免?谢谢!
我正在尝试在基于Tomcat的Web应用程序中使用log4j2,因此我添加了log4j web模块以及其他必要的jar包。但是当停止这个Web应用程序时,我会遇到以下异常。
FATAL Unable to register shutdown hook because JVM is shutting down
正如Pouriya的回答所解释的那样,您可能在没有适当的关闭挂钩的情况下尝试使用Log4j2。 由于您正在谈论Tomcat Web应用程序,我假设您正在使用Servlets。(如果不是,请参见下面的第二部分)。然后,您必须在ContextListener中声明这个:
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent evt) {
String appenderName = evt.getServletContext().getInitParameter("log4jContextName");
File file = new File(evt.getServletContext().getInitParameter("log4jConfiguration"));
if(!file.exists()){
logger = LogManager.getRootLogger();
} else{
logger = LogManager.getLogger(appenderName);
}
}
}
@Override
public void contextDestroyed(ServletContextEvent evt) {
// You don't really need to do anything here, about the logger.
// The log4j2 JAR will handle it properly.
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app ... >
<context-param>
<param-name>log4jContextName</param-name>
<param-value>myApplication</param-value>
</context-param>
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/the/path/to/your/log4j.properties.file</param-value>
</context-param>
</web-app>
public static void main( String[] args ) {
...
File file = new File(logFileName);
if(!file.exists()){
logger = LogManager.getRootLogger();
} else {
System.setProperty("log4j.configurationFile", file.toURI().toURL().toString());
logger = LogManager.getLogger("yourProgramName");
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
logger.info("Shutting down - closing application");
// Shut down everything (e.g. threads) that you need to.
// then shut down log4j
if( LogManager.getContext() instanceof LoggerContext ) {
logger.debug("Shutting down log4j2");
Configurator.shutdown((LoggerContext)LogManager.getContext());
} else
logger.warn("Unable to shutdown log4j2");
// logger not usable anymore
System.out.println("Done.");
}
});
}
当你的应用程序结束时(例如,调用System.exit(0)
),关闭挂钩将被调用。
你还需要在Log4J2配置文件中添加以下内容:
XML版本:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration shutdownHook="disable">
...
</Configuration>
JSON版本:
{"configuration":
{
"shutdownHook":"disable",
....
}
}
<Configuration status="WARN" monitorInterval="30" shutdownHook="disable"> ... </ Configuration>
有很多说明关于如何使用关闭挂钩及其好处。
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { //进行清理操作 } });
- Pouriya Zarbafian