Java Tutorial/Log/Log Handler

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Add Multiple Handlers to a logger

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("MultipleHandlers2");
  public static void main(String[] args) throws Exception {
    FileHandler logFile = new FileHandler("MultipleHandlers2.xml");
    logger.addHandler(logFile);
    logger.addHandler(new ConsoleHandler());
    logger.setUseParentHandlers(false);
    logger.warning("Output to multiple handlers");
  }
}





A file handler that appends.

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    boolean append = true;
    FileHandler handler = new FileHandler("my.log", append);
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





Alternate XML by using FileHandler

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler handler = new FileHandler("alterxml.xml");
    Logger logger = Logger.getLogger("your.logging");
    logger.addHandler(handler);
    logger.log(Level.INFO, "alternative xml");
  }
}





Create a memory handler with a memory of 100 records and dumps the records into the file my.log

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler fhandler = new FileHandler("my.log");
    int numRec = 100;
    MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.OFF) {
      public synchronized void publish(LogRecord record) {
        super.publish(record);
        push();
      }
    };
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(mhandler);
  }
}





Flush File Handler and Logger

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] args) throws Exception {
    FileHandler handler = null;
    Logger logger = Logger.getLogger("logging");
    handler = new FileHandler("pattern", 1000, 2);
    logger.addHandler(handler);
    LogRecord record = new LogRecord(Level.INFO, "Logged in a file...");
    logger.log(record);
    handler.flush();
    handler.close();
  }
}





How to write custom handler

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("CustomHandler");
  private static List strHolder = new ArrayList();
  public static void main(String[] args) {
    logger.addHandler(new Handler() {
      public void publish(LogRecord logRecord) {
        strHolder.add(logRecord.getLevel() + ":");
        strHolder.add(logRecord.getSourceClassName() + ":");
        strHolder.add(logRecord.getSourceMethodName() + ":");
        strHolder.add("<" + logRecord.getMessage() + ">");
        strHolder.add("\n");
      }
      public void flush() {
      }
      public void close() {
      }
    });
    logger.warning("Logging Warning");
    logger.info("Logging Info");
    System.out.print(strHolder);
  }
}





Limiting the Size of a Log by Using a Rotating Sequence of Files

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a file handler that uses 3 logfiles, each with a limit of 1Mbyte
    String pattern = "my%g.log";
    int limit = 1000000; // 1 Mb
    int numLogFiles = 3;
    FileHandler fh = new FileHandler(pattern, limit, numLogFiles);
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(fh);
  }
}





Limiting the Size of a Log File

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a file handler with a limit of 1 megabytes
    String pattern = "my.log";
    int limit = 1000000; // 1 Mb
    FileHandler fh = new FileHandler("my.log", limit, 1);
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(fh);
  }
}





Memory Handler Demo

import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String args[]) throws Exception {
    Logger logger = Logger.getLogger("your.logging");
    ConsoleHandler handler = new ConsoleHandler();
    MemoryHandler mHandler = new MemoryHandler(handler, 10, Level.ALL);
    logger.addHandler(mHandler);
    logger.setUseParentHandlers(false);
    LogRecord record1 = new LogRecord(Level.SEVERE, "This is SEVERE level message");
    LogRecord record2 = new LogRecord(Level.WARNING, "This is WARNING level message");
    logger.log(record1);
    logger.log(record2);
  }
}





Socket Handler Demo

import java.util.logging.Logger;
import java.util.logging.SocketHandler;
public class Main {
  public static void main(String args[]) throws Exception{
    SocketHandler handler = null;
    Logger logger = Logger.getLogger("your.logging");
    handler = new SocketHandler("127.0.0.1", 8080);
    logger.addHandler(handler);
    logger.warning("SocketHandler is working...");
  }
}





Stream Handler

import java.io.OutputStream;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
public class Main {
  public static void main(String[] args) {
    Logger logger = Logger.getLogger("logging");
    OutputStream outStream = System.out;
    StreamHandler handler = new StreamHandler(outStream, new SimpleFormatter());
    logger.addHandler(handler);
    logger.setUseParentHandlers(false);
    logger.info("StreamHandler is working�");
  }
}





The Patterns in FileHandler

Expression       Meaning
/                The path separator of the local OS
%t               A directory suitable for storing temporary logging files, such as the temp directory of the OS
%h               A directory such as the "user.home" location, which is suitable to store user-specific data in the system
%g               A log generation number to rotate log files
%u               A number to make a log file unique to avoid any conflicts
%%               A literal percent sign





Use ConsoleHandler

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("MultipleHandlers");
  public static void main(String[] args) throws Exception {
    FileHandler logFile = new FileHandler("MultipleHandlers.xml");
    logger.addHandler(logFile);
    logger.addHandler(new ConsoleHandler());
    logger.warning("Output to multiple handlers");
  }
}





Use Logger with simple formatter and FileHander

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Main {
  public static void main(String[] args) throws Exception {
    Logger logger = Logger.getLogger("MyLog");
    FileHandler fh;
    fh = new FileHandler("c:\\MyLogFile.log", true);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.log(Level.WARNING, "My first log");
  }
}





Using FileHandler to log a message

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class LoggingExample1 {
  public static void main(String args[])  {
    try {
      LogManager lm = LogManager.getLogManager();
      Logger logger;
      FileHandler fh = new FileHandler("log_test.txt");
      logger = Logger.getLogger("LoggingExample1");
      lm.addLogger(logger);
      logger.setLevel(Level.INFO);
      fh.setFormatter(new XMLFormatter());
      logger.addHandler(fh);
       //logger.setUseParentHandlers(false);
      logger.log(Level.INFO, "test 1");
      logger.log(Level.INFO, "test 2");
      logger.log(Level.INFO, "test 3");
      fh.close();
    } catch (Exception e) {
      System.out.println("Exception thrown: " + e);
      e.printStackTrace();
    }
  }
}





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





Window Handler: display log message in a window(JFrame)

import java.util.logging.ErrorManager;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class LogWindow extends JFrame {
  private JTextArea textArea = new JTextArea();
  public LogWindow() {
    super("");
    setSize(300, 300);
    add(new JScrollPane(textArea));
    setVisible(true);
  }
  public void showInfo(String data) {
    textArea.append(data);
    this.validate();
  }
}
class WindowHandler extends Handler {
  private LogWindow window = null;
  private Formatter formatter = null;
  private Level level = null;
  private static WindowHandler handler = null;
  private WindowHandler() {
    LogManager manager = LogManager.getLogManager();
    String className = this.getClass().getName();
    String level = manager.getProperty(className + ".level");
    setLevel(level != null ? Level.parse(level) : Level.INFO);
    if (window == null)
      window = new LogWindow();
  }
  public static synchronized WindowHandler getInstance() {
    if (handler == null) {
      handler = new WindowHandler();
    }
    return handler;
  }
  public synchronized void publish(LogRecord record) {
    String message = null;
    if (!isLoggable(record))
      return;
    message = getFormatter().format(record);
    window.showInfo(message);
  }
  public void close() {
  }
  public void flush() {
  }
}
public class Main {
  private WindowHandler handler = null;
  private Logger logger = null;
  public Main() {
    handler = WindowHandler.getInstance();
    logger = Logger.getLogger("logging.handler");
    logger.addHandler(handler);
  }
  public void logMessage() {
    logger.info("Hello from ...");
  }
  public static void main(String args[]) {
    Main demo = new Main();
    demo.logMessage();
    WindowHandler h = WindowHandler.getInstance();
    LogRecord r = new LogRecord(Level.WARNING, "The Handler publish method...");
    h.publish(r);
  }
}





Writing Log Records Only After a Condition Occurs

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler fhandler = new FileHandler("my.log");
    int numRec = 100;
    MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.SEVERE);
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(mhandler);
  }
}





Writing Log Records to a Log File

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler handler = new FileHandler("my.log");
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





Writing Log Records to Standard Error

import java.util.logging.ConsoleHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    ConsoleHandler handler = new ConsoleHandler();
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}