Merge branch 'master' of ../controller
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / concurrent / LoggingThreadUncaughtExceptionHandler.java
1 /*
2  * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util.concurrent;
9
10 import java.lang.Thread.UncaughtExceptionHandler;
11 import java.util.Objects;
12 import org.slf4j.Logger;
13
14 /**
15  * Thread's UncaughtExceptionHandler which logs to slf4j.
16  *
17  * @author Michael Vorburger.ch
18  */
19 @SuppressWarnings({"checkstyle:LoggerVariableName", "LoggerVariableModifiers"})
20 public final class LoggingThreadUncaughtExceptionHandler implements UncaughtExceptionHandler {
21
22     // This class is also available in infrautils (but yangtools cannot depend on infrautils)
23     // as org.opendaylight.infrautils.utils.concurrent.LoggingThreadUncaughtExceptionHandler
24
25     /**
26      * Factory method to obtain an instance of this bound to the passed slf4j Logger.
27      */
28     public static UncaughtExceptionHandler toLogger(Logger logger) {
29         return new LoggingThreadUncaughtExceptionHandler(logger);
30     }
31
32     private final Logger logger;
33
34     private LoggingThreadUncaughtExceptionHandler(Logger logger) {
35         this.logger = Objects.requireNonNull(logger, "logger");
36     }
37
38     @Override
39     public void uncaughtException(Thread thread, Throwable throwable) {
40         logger.error("Thread terminated due to uncaught exception: {}", thread.getName(), throwable);
41     }
42 }