pongy20
pongy20

Reputation: 21

How to log all uncaught exceptions in java using log4j

I want to log the exceptions in my server side java program. Is there any way to catch all exceptions that have not been caught using an existing try catch?

I thought about doing a try catch in my main executor and log the exception the catch but I got a problem: exceptions on other threads haven't been caught.

Upvotes: 1

Views: 1335

Answers (1)

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16185

Each thread can have an UncaughtExceptionHandler, which is called when an exception reaches the bottom of the thread's call stack. The default implementation prints a message on the standard error.

You can change the default handler with:

  private static final Logger logger = LogManager.getLogger();

  public static void main(String[] args) throws IOException {
    Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
      logger.warn("Uncaught exception in thread {}.", t, e);
    });

Upvotes: 3

Related Questions