Using Regular Expressions based on StreamHandler : Log Handler « Log « Java Tutorial






import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainClass {
  public static void main(String args[]) {
    Logger log = Logger.getAnonymousLogger();
    setLoggerhandler(log);

    log.finest(new Exception().toString());
  }

  public static void setLoggerhandler(Logger logger) {
    Handler handler = new ExceptionHandler();
    logger.addHandler(handler);

    logger.setLevel(Level.ALL);
  }
}

class ExceptionHandler extends StreamHandler {
  public void publish(LogRecord record) {
    String msg = record.getMessage();
    int exceptionIndex = msg.indexOf("Exception");

    if (exceptionIndex > -1) {
      Pattern pattern = Pattern.compile("(.*Exception.*)");

      Matcher matcher = pattern.matcher(msg);

      if (matcher != null && matcher.find()) {
        String err = "EXCEPTION FOUND " + matcher.group(1);
        System.out.println(err);
      }
    }
  }
}








35.5.Log Handler
35.5.1.Use ConsoleHandler
35.5.2.Using FileHandler to log a message
35.5.3.Add Multiple Handlers to a logger
35.5.4.How to write custom handler
35.5.5.Stream Handler
35.5.6.Memory Handler Demo
35.5.7.Socket Handler Demo
35.5.8.Using Regular Expressions based on StreamHandler
35.5.9.Writing Log Records to a Log File
35.5.10.A file handler that appends.
35.5.11.Writing Log Records to Standard Error
35.5.12.Writing Log Records Only After a Condition Occurs
35.5.13.Create a memory handler with a memory of 100 records and dumps the records into the file my.log
35.5.14.Flush File Handler and Logger
35.5.15.The Patterns in FileHandler
35.5.16.Limiting the Size of a Log File
35.5.17.Limiting the Size of a Log by Using a Rotating Sequence of Files
35.5.18.Use Logger with simple formatter and FileHander
35.5.19.Alternate XML by using FileHandler
35.5.20.Window Handler: display log message in a window(JFrame)