Java by API/java.util.logging/StreamHandler

Материал из Java эксперт
Перейти к: навигация, поиск

extends StreamHandler

  

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 Main {
  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.rupile("(.*Exception.*)");
      Matcher matcher = pattern.matcher(msg);
      if (matcher != null && matcher.find()) {
        String err = "EXCEPTION FOUND " + matcher.group(1);
        System.out.println(err);
      }
    }
  }
}





StreamHandler: flush()

  
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.XMLFormatter;
public class Main {
  public static void main(String args[]) throws Exception{
    XMLFormatter formatter = new XMLFormatter();
    LogRecord record = new LogRecord(Level.INFO, "XML message..");
    FileHandler handler = new FileHandler("newxml.xml");
    handler.setFormatter(formatter);
    handler.publish(record);
    handler.flush();
  }
}