Search code examples
javastack-tracesystemexit

Is there a way to log stacktrace which called System.exit in Java


I think there is a way to do this with SecurityManager, but I don't want to introduce it in an App just for this.

Is there a way to catch and log stacktrace of what called exit() using some other solution?


Solution

  • How about using shutdown hook? It could be like this:

    Thread printStackTracesOnShutdownHook = new Thread(() -> {
        LOG.info("Shutdown hook called");
        for (Map.Entry<Thread, StackTraceElement[]> pair : 
                 Thread.getAllStackTraces().entrySet()) {
            LOG.info(pair.getKey() + " : " + Arrays.toString(pair.getValue()));
        }
    });
    
    Runtime.getRuntime().addShutdownHook(printStackTracesOnShutdownHook);
    

    You can add this code somewhere in your application (where it will be executed). Then on shutdown printStackTracesOnShutdownHook will write to logs all stackTraces. And you will be able to find from these stackTraces where System.exit() was called.