简体   繁体   中英

Handle all exceptions

I used logback for logging java application. How to i can handle all exceptions in my app with logback

My test config

    <appender name="exceptions" class="ch.qos.logback.core.FileAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>java.lang.Exception.class.isInstance(throwable)</expression>
            </evaluator>
            <onMatch>ACCEPT</onMatch>
        </filter>
        <file>exceptions.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
            <immediateFlush>false</immediateFlush>
        </encoder>
    </appender>

Assuming you mean catching all exceptions, even those that are not caught: you can define an uncaught exceptions handler in your code, as early as possible:

private static void setDefaultUncaughtExceptionHandler() {
    try {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("Uncaught Exception detected in thread " + t, e);
            }
        });
    } catch (SecurityException e) {
        LOGGER.error("Could not set the Default Uncaught Exception Handler", e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM