'Why Log4j2 Doesn't Log Before System.exit(1)

When I use System.exit(1) after logging an error via Log4j2, the system close but the log doesn't be written at log files. In normal situations without using System.exit(1) logging works fine and logs everything. Only when I use System.exit(1) after a log, the log doesn't be written to log files. Why is that?

This code works fine and logs:

loggerUtil.error("something went wrong");

This code doesn't log:

loggerUtil.error("something went wrong");
System.exit(1);

I found that the system exits before waits ending logging operations. What should I do or what is the solution? Is there anything like System.waitAndExit()?



Solution 1:[1]

Below code did the trick for me:

   Runtime.getRuntime().addShutdownHook(new Thread() {
       @Override
       public void run() {
           LogManager.shutdown();
       }        
   });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vikas Tandon