Suppose a shutdownHook as :
class ShutdownHolder extends Thread {
public void run() {
Logger logger = LoggerFactory.getCoreLogger(ShutdownHolder.class);
try {
logger.info("Shutdown hook is running...");
doSomething();
logger.info("Shutdown hook end.");
} catch(Exception e) {
logger.severe("Unexpected ERROR during shutdown", e);
}
}
}
How to avoid that logger doesn’t be closed before ShutdownHook ends ?
For example, doSomething() method could call several methods on other accessible classes also writening logs. I don’t want to skip all these logs.
So aside from some reflection hacks, I don’t see an easy way to do this unfortunately. Under 1.6 JDK the shutdown hooks are stored in an
IdentityHashmapwhich provides no guaranteed order. In effect the shutdown hooks are called in random order depending on the internals of that map.In terms of reflection, I tried to do the following but
hookMapcomes out as null for me. If you can get it to work then you may be able to remove the log4j hook and call it manually at the end of your hook or something.However, I would strongly recommend doing something other than a shutdown hook. How about calling your own hooks before
mainfinishes? For us, we use Spring and theDisposableBeanpattern heavily. Those beans are called in reverse order from when the classes were instantiated so anything that depends on the loggers still has the logger when it shuts down.Hope this helps.