'How to 'catch' a log written by external library (Java/Spring boot)

I have the following situation:

I'm using an external library, which executes some logic. The thing is, during this execution something may go wrong. When this kind of situation occurs, the warning log is printed in the terminal. For my needs, I need to treat this warning as an error and handle it by myself. I can't edit the existing code in a library. I need some solution to 'catch' this warning log that, was written. Do you have any solution for that? I'm using Java with spring boot

The example code structure:

class ExternalLibraryClass { // <- this class is read-only, I can't edit it 
   public void execute() {
     // logic
     if(something wrong) {
       log.warn("something wrong has happened");
     }
   }
}

class myClass {

  public static void main(String[] args) {
     new ExternalLibraryClass().execute();

 //  if('warning log has been written in the terminal') {
 //      handle_this_warnig_like_an_error();
 //    }
  }
}
  


Solution 1:[1]

The objective of logging is not to be used in these kind of situations, but if you want to follow that path, you can create an Appender that you attach to the root log for example. Don't forget that the log level must be set at least to the level that you expect the message to be logged (or specify the level for that class).

Assuming that you are using slf4j and logback, you can do this (adapt to other provider if needed).

    import ch.qos.logback.classic.Logger;
    import org.slf4j.LoggerFactory;
    ...
    private static final LoggingInterceptorAppender loggingInterceptorAppender = new LoggingInterceptorAppender();
    ...
    
    void addLoggerInterceptorAppender(){
       Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    
       if (root.getAppender("LOGGING_INTERCEPTOR_APPENDER_NAME") == null) {
          root.addAppender(loggingInterceptorAppender);
       }
    }

Then you need a class that implements Appender.

import ch.qos.logback.core.Appender;
import ch.qos.logback.classic.spi.ILoggingEvent;

class LoggingInterceptorAppender implements Appender<ILoggingEvent> {

  @Override
  public String getName() {

    return "LOGGING_INTERCEPTOR_APPENDER_NAME";
  }

  // Lots of @Override methods


  @Override
  public void doAppend(ILoggingEvent iLoggingEvent) throws LogbackException {

    // Here you can check the event and see if it is the one that you want
    // and perform the logic or call whatever you want.
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pringi