How can I detect when an Exception's been thrown globally in Java?

后端 未结 10 457
自闭症患者
自闭症患者 2020-11-30 02:30

How can I detect when an Exception has been thrown anywhere in my application?

I\'m try to auto-magically send myself an email whenever an exception is thrown anywhe

10条回答
  •  一整个雨季
    2020-11-30 03:18

    In my current project I faced the similar requirement regarding the errors detection. For this purpose I have applied the following approach: I use log4j for logging across my app, and everywhere, where the exception is caught I do the standard thing: log.error("Error's description goes here", e);, where e is the Exception being thrown (see log4j documentation for details regarding the initialization of the "log"). In order to detect the error, I use my own Appender, which extends the log4j AppenderSkeleton class:

    import org.apache.log4j.AppenderSkeleton;
    import org.apache.log4j.spi.LoggingEvent;
    
    public class ErrorsDetectingAppender extends AppenderSkeleton {
    
        private static boolean errorsOccured = false;
    
        public static boolean errorsOccured() {
            return errorsOccured;
        }
    
        public ErrorsDetectingAppender() {
            super();
        }
    
        @Override
        public void close() {
            // TODO Auto-generated method stub
        }
    
        @Override
        public boolean requiresLayout() {
            return false;
        }
    
        @Override
        protected void append(LoggingEvent event) {
            if (event.getLevel().toString().toLowerCase().equals("error")) {
                System.out.println("-----------------Errors detected");
                this.errorsOccured = true;
            }
        }
    }
    

    The log4j configuration file has to just contain a definition of the new appender and its attachement to the selected logger (root in my case):

    log4j.rootLogger = OTHER_APPENDERS, ED
    log4j.appender.ED=com.your.package.ErrorsDetectingAppender
    

    You can either call the errorsOccured() method of the ErrorsDetectingAppender at some significant point in your programs's execution flow or react immidiately by adding functionality to the if block in the append() method. This approach is consistent with the semantics: things that you consider errors and log them as such, are detected. If you will later consider selected errors not so important, you just change the logging level to log.warn() and report will not be sent.

提交回复
热议问题