Java log: Log and Window(JFrame, frame) : Log « Language Basics « Java






Java log: Log and Window(JFrame, frame)

Java log: Log and Window(JFrame, frame)
    
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996

*/

import java.util.logging.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

class LogWindow extends JFrame {
  private int width;

  private int height;

  private JTextArea textArea = null;

  private JScrollPane pane = null;

  public LogWindow(String title, int width, int height) {
    super(title);
    setSize(width, height);
    textArea = new JTextArea();
    pane = new JScrollPane(textArea);
    getContentPane().add(pane);
    setVisible(true);
  }

  /**
   * This method appends the data to the text area.
   * 
   * @param data
   *            the Logging information data
   */
  public void showInfo(String data) {
    textArea.append(data);
    this.getContentPane().validate();
  }
}

class WindowHandler extends Handler {
  //the window to which the logging is done
  private LogWindow window = null;

  private Formatter formatter = null;

  private Level level = null;

  //the singleton instance
  private static WindowHandler handler = null;

  /**
   * private constructor, preventing initialization
   */
  private WindowHandler() {
    configure();
    if (window == null)
      window = new LogWindow("Logging window", 500, 200);
  }

  /**
   * The getInstance method returns the singleton instance of the
   * WindowHandler object It is synchronized to prevent two threads trying to
   * create an instance simultaneously. @ return WindowHandler object
   */

  public static synchronized WindowHandler getInstance() {

    if (handler == null) {
      handler = new WindowHandler();
    }
    return handler;
  }

  /**
   * This method loads the configuration properties from the JDK level
   * configuration file with the help of the LogManager class. It then sets
   * its level, filter and formatter properties.
   */
  private void configure() {
    LogManager manager = LogManager.getLogManager();
    String className = this.getClass().getName();
    String level = manager.getProperty(className + ".level");
    String filter = manager.getProperty(className + ".filter");
    String formatter = manager.getProperty(className + ".formatter");

    //accessing super class methods to set the parameters
    setLevel(level != null ? Level.parse(level) : Level.INFO);
    setFilter(makeFilter(filter));
    setFormatter(makeFormatter(formatter));

  }

  /**
   * private method constructing a Filter object with the filter name.
   * 
   * @param filterName
   *            the name of the filter
   * @return the Filter object
   */
  private Filter makeFilter(String filterName) {
    Class c = null;
    Filter f = null;
    try {
      c = Class.forName(filterName);
      f = (Filter) c.newInstance();
    } catch (Exception e) {
      System.out.println("There was a problem to load the filter class: "
          + filterName);
    }
    return f;
  }

  /**
   * private method creating a Formatter object with the formatter name. If no
   * name is specified, it returns a SimpleFormatter object
   * 
   * @param formatterName
   *            the name of the formatter
   * @return Formatter object
   */
  private Formatter makeFormatter(String formatterName) {
    Class c = null;
    Formatter f = null;

    try {
      c = Class.forName(formatterName);
      f = (Formatter) c.newInstance();
    } catch (Exception e) {
      f = new SimpleFormatter();
    }
    return f;
  }

  /**
   * This is the overridden publish method of the abstract super class
   * Handler. This method writes the logging information to the associated
   * Java window. This method is synchronized to make it thread-safe. In case
   * there is a problem, it reports the problem with the ErrorManager, only
   * once and silently ignores the others.
   * 
   * @record the LogRecord object
   *  
   */
  public synchronized void publish(LogRecord record) {
    String message = null;
    //check if the record is loggable
    if (!isLoggable(record))
      return;
    try {
      message = getFormatter().format(record);
    } catch (Exception e) {
      reportError(null, e, ErrorManager.FORMAT_FAILURE);
    }

    try {
      window.showInfo(message);
    } catch (Exception ex) {
      reportError(null, ex, ErrorManager.WRITE_FAILURE);
    }

  }

  public void close() {
  }

  public void flush() {
  }
}

public class CustomHandlerDemo {
  private WindowHandler handler = null;

  private Logger logger = null;

  public CustomHandlerDemo() {
    handler = WindowHandler.getInstance();
    //obtaining a logger instance and setting the handler
    logger = Logger.getLogger("sam.logging.handler");
    logger.addHandler(handler);
  }

  /**
   * This method publishes the log message
   */
  public void logMessage() {
    logger.info("Hello from WindowHandler...");
  }

  public static void main(String args[]) {
    //logging with the help of a logger
    CustomHandlerDemo demo = new CustomHandlerDemo();
    demo.logMessage();
    //using the handler.publish() to log
    WindowHandler h = WindowHandler.getInstance();
    LogRecord r = new LogRecord(Level.WARNING,
        "The Handler publish method...");
    h.publish(r);
  }
}


           
         
    
    
    
  








Related examples in the same category

1.Log levelLog level
2.Simple Log Formatter ExampleSimple Log Formatter Example
3.Log to file with FileHandler and SimpleFomatterLog to file with FileHandler and SimpleFomatter
4.Log multiple HandlersLog multiple Handlers
5.Log multiple Handlers 2Log multiple Handlers 2
6.Override LogRecord toString()Override LogRecord toString()
7.Email LoggerEmail Logger
8.Log To File with FileHandlerLog To File with FileHandler
9.Logging LevelsLogging Levels
10.Creating a Custom Log Level
11.Logging Level ManipulationLogging Level Manipulation
12.Configure LoggingConfigure Logging
13.How to write custom Log handlerHow to write custom Log handler
14.Log Client Filter
15.Log HTML Table Formatter
16.Logging Example 1Logging Example 1
17.Basic Logging Example
18.Java Log:Basic Logging Java Log:Basic Logging
19.Java log: Hierarchy loggingJava log: Hierarchy logging
20.Java log: various log methodsJava log: various log methods
21.Java log: Stream Handler DemoJava log: Stream Handler Demo
22.Java log: File Handler DemoJava log: File Handler Demo
23.Java log: Memory Handler DemoJava log: Memory Handler Demo
24.Java log: Socket Handler Demo
25.Java log: Basic logging 2Java log: Basic logging 2
26.Java log: Logging Server
27.Java log: log filterJava log: log filter
28.Java log: XML log
29.Java log: alternate XML logJava log: alternate XML log
30.Java log: Localize LoggingJava log: Localize Logging
31.Java log: Custom XML FormatterJava log: Custom XML Formatter
32.Java log: Remote Config Reader
33.File Logger
34.Setting the Formatter of a Logger Handler
35.Memory Handler Demo
36.Socket Handler Demo
37.XMLFormatter based Logging
38.#define the properties for the SocketHandler
39.Custom filter
40.Using Regular Expressions based on StreamHandler
41.The Quintessential Logging Program
42.Determining If a Message Will Be Logged
43.Logging a Method Call
44.Logging an Exception
45.Minimizing the Impact of Logging Code
46.Preventing a Logger from Forwarding Log Records to Its Parent
47.Writing Log Records to a Log File
48.A file handler that appends.
49.Writing Log Records to Standard Error
50.Writing Log Records Only After a Condition Occurs
51.Create a memory handler with a memory of 100 records and dumps the records into the file my.log
52.Setting a Filter on a Logger Handler
53.Comparing Log Levels: To compare the severity of two logging levels, use Level.intValue().
54.Creating a Custom Formatter for a Logger Handler
55.Limiting the Size of a Log File
56.Limiting the Size of a Log by Using a Rotating Sequence of Files
57.Configuring Logger Default Values with a Properties File
58.Determining When the Logging Configuration Properties are Reread
59.Handling Errors While Parsing an XML File
60.An example of a program providing the functionality of logging
61.Use Logger with simple formatter and FileHandler
62.Logger with XMLFormatter and FileHandler
63.Stream Handler
64.The Patterns in FileHandler
65.Flush File Handler and Logger
66.Config Demo
67.config.properties
68.Alternate XML by using FileHandler
69.Localized Logging
70.Define your own Custom Formatter
71.Remote ConfigReader with URLConnection
72.Window Handler: display log message in a window(JFrame)
73.Create log with package nameCreate log with package name
74.Logger Demo
75.Return a message for logging.
76.A simple wrapper around JDK logging facilities
77.A modification of the image viewer program that logs various events
78.A class helper for logging service.
79.Logging Thread Pool
80.Logging Thread