JMU
Logging in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Overview
Key Elements of java.util.logging
The Process
  1. The application calls a method in a Logger object.
  2. The Logger creates a LogRecord.
  3. The Logger (perhaps after checking a log level and/or Filter) passes the LogRecord to a Handler.
  4. The Handler uses a Formatter is used to format the LogRecord.
Log Levels
Logging Methods
Output/Transmission
An Example

Logging Basics

javaexamples/logging/Driver.java
import java.io.*;
import java.util.logging.*;


/**
 * An example that demonstrates how to use some of the
 * basic features of the java.util.logging package
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Driver
{


    /**
     * The entry point
     *
     * @Param args   The command line arguments (ignored)
     */
    public static void main(String[] args) throws Exception
    {
       FileHandler    handler;
       int            result;
       Logger         logger;
       


       // Get the default logger (alternatively, could create
       // one for this application)
       logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);


       // Create a FileHandler
       handler = new FileHandler("mylog.txt");   
       

       // Send logger output to our FileHandler
       logger.addHandler(handler);

       // Set the formatter
       handler.setFormatter(new SimpleFormatter());
        

       // Request that everything above this level gets logged.
       logger.setLevel(Level.FINE);

       // Log a simple INFO message.
       logger.log(Level.FINE, "Starting");

       try 
       {
          result = 1 / 0;
       } 
       catch (ArithmeticException ae) 
       {
          logger.log(Level.WARNING, "Trouble dividing", ae);
       }


       logger.log(Level.FINER, "Finished");
    }
}