2013-08-28 103 views
1

我使用logback來記錄Java應用程序。如何我可以處理我的應用程序的所有異常與logback處理所有異常

測試配置

<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> 

回答

4

假設你的意思捕獲所有異常,即使是那些沒有被卡住:你可以定義一個未捕獲的異常處理程序您的代碼儘早:

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); 
    } 
}