Java ScreenShot

Screenshot Core Java 2: Volume I - Fundamentals

Table of Contents
 11.  Exceptions and Debugging


Every Java programmer is familiar with the process of inserting calls to System.out.println into troublesome code to gain insight into program behavior. Of course, once you have figured out the cause of trouble, you remove the print statements, only to put them back in when the next problem surfaces. The logging API of SDK 1.4 is designed to overcome this problems. Here are the principal advantages of the API.

  • It is easy to suppress all log records, or just those below a certain level, and just as easy to turn them back on.
  • Suppressed logs are very cheap, so that there is only a minimal penalty for leaving the logging code in your app.
  • Log records can be directed towards different handlers, for display in the console, storage in a file, and so on.
  • Both loggers and handlers can filter records. Filters discard boring log entries, using any criteria supplied by the filter implementor.
  • Log records can be formatted in different ways, for example in plain text or XML.
  • apps can use multiple loggers, with hierarchical names such as com.mycompany.myapp, similar to package names.
  • By default, the logging configuration is controlled by a configuration file. apps can replace this mechanism if desired.

Basic Logging

Let's get started with the simplest possible case. The logging system manages a default logger with name "global". Get a reference to it, and then issue calls to the info method:

Logger logger = Logger.getLogger("global");"File->Open menu item selected");

By default, the record is printed like this:

Feb 2, 2002 10:12:15 PM LoggingImageViewer fileOpen INFO: File->Open menu item selected

(Note that the time and the names of the calling class and method are automatically included.) But if you call


at an appropriate place (such as the beginning of main), then the record is suppressed. In other words, you can simply print debugging messages with Logger.getLogger("global").info instead of System.out.println.

Advanced Logging

Now that you have seen "logging for dummies," let's go on to industrial-strength logging. In a professional app, one wouldn't want to log all records to a single global logger. Instead, you can define your own loggers. When you request a logger with a given name for the first time, it is created.

Logger myLogger = Logger.getLogger("com.mycompany.myapp");

Subsequent calls to the same name yield the same logger object. Similar to package names, logger names are hierarchical. In fact, they are more hierarchical than packages. There is no semantic relationship between a package and its parent, but logger parents and children share certain properties. For example, if you set the log level on the logger "com.mycompany", then the child loggers inherit that level. There are seven logging levels:

  • INFO
  • FINE

By default, the top three levels are actually logged. You can set a different level, for example


Now all levels of FINE and higher are logged. You can also use Level.ALL to turn on logging for all levels or Level.OFF to turn all logging off. There are logging methods for all levels, such as


and so on. Alternatively, you can use the log method and supply the level, such as

logger.log(Level.FINE, message);

Java graphics exclamatory_icon.gif

The default logging configuration logs all records with level of INFO or higher. Therefore, you should use the levels CONFIG, FINE, FINER, and FINEST for debugging messages that are useful for diagnostics but meaningless to the program user.

Java graphics caution_icon.gif

If you set the logging level to a value finer than INFO, then you also need to change the log handler configuration. The default log handler suppresses messages below INFO. See the next section for details.

The default log record shows the name of the class and method that contains the logging call, as inferred from the call stack. However, if the virtual machine optimizes execution, accurate call information may not be available. You can use the logp method to give the precise location of the calling class and method. The method signature is
void logp(Level l, String className, String methodName,
 String message)

There are convenience methods for tracing execution flow:

void entering(String className, String methodName)
void entering(String className, String methodName, Object param)
void entering(String className, String methodName,
 Object[] params)
void exiting(String className, String methodName)
void exiting(String className, String methodName, Object result)

For example,

int read(String file, String pattern)
 entering("com.mycompany.mylib.Reader", "read",
 new Object[] { file, pattern });
 . . .
 exiting("com.mycompany.mylib.Reader", "read", count);
 return count;

These calls generate log records of level FINER that start with the strings ENTRY and RETURN. A common use for logging is to log unexpected exceptions. There are two convenience methods that include a description of the exception in the log record.

void throwing(String className, String methodName, Throwable t)
void log(Level l, String message, Throwable t)

Typical uses are

if (. . .)
 IOException exception = new IOException(". . .");
 throwing("com.mycompany.mylib.Reader", "read", exception);
 throw exception;


 . . .
catch (IOException e)
 "Reading image", e);

The throwing call logs a record with level FINER and a message that starts with THROW.

Changing the Log Manager Configuration

You can change various properties of the logging system by editing a logging properties file. The default configuration file is located at


If you want to use another file, you need to set the java.util.logging.config.file property to the file location by starting your app with

java -Djava.util.logging.config.file=file MainClass

Java graphics caution_icon.gif

Calling System.setProperty(java.util.logging.config.file, file) in main has no effect since the log manager is initialized during VM startup, before main executes.

To change the default logging level, edit the configuration file and modify the line

You can specify the logging levels for your own loggers by adding lines such as


That is, append the .level suffix to the logger name. As you will see later in this section, the loggers don't actually send the messages to the console—that is the job of the handlers. Handlers also have levels. To see fine messages on the console, you also need to set


Java graphics caution_icon.gif

The settings in the log manager configuration are not system properties. Starting a program with -Dcom.mycompany.myapp.level=FINE does not have any influence on the logger.

Java graphics notes_icon.gif

The logging properties file is processed by the java.util.logging.LogManager class. It is possible to specify a different log manager by setting the java.util.logging.manager system property to the name of a subclass. Alternatively, you can keep the standard log manager and still bypass the initialization from the logging properties file. Set the java.util.logging.config.class system property to the name of a class that sets log manager properties in some other way. See the API documentation for the LogManager class for more information.


You may want to localize logging messages so that they are readable for international users. Internationalization of apps is the topic of of Volume 2. Briefly, here are the points to keep in mind when localizing logging messages. Localized apps contain locale-specific information in resource bundles. A resource bundle consists of a set of tables for various locales (such as United States or Germany). Each table maps resource names into objects. For example, a resource bundle may map the string "reading_file" into strings "Reading file" or "Achtung! Datei wird eingelesen." A program may contain multiple resource bundles, perhaps one for menus and another for log messages. Each resource bundle has a name (such as "log_messages"). of Volume 2 explains how to prepare resource bundles and how to attach them to a program. When requesting a logger, you can specify a resource bundle:

Logger logger = Logger.getLogger(loggerName, bundleName);

Then you specify the resource bundle key, not the actual message string, for the log message."reading_file");

Often, you need to include arguments into localized messages. Then the message should contain placeholders {0}, {1}, and so on. For example, you may want to include the file name with a "reading file" log message. The localized messages would be

Reading file {0}.
Achtung! Datei {0} wird eingelesen.

For more information about these placeholders, see of Volume 2 or the API documentation of the MessageFormat class. There are convenience log methods that take a single parameter, or an array of parameters.

logger.log(Level.INFO, "reading_file", fileName);
logger.log(Level.INFO, "renaming_file",
 new Object[] { oldName, newName });

Finally, there is a set of logrb methods (log with resource bundle) that let you specify the resource bundle name explicitly. You would need these methods if your localized strings are distributed over multiple bundles. For example,

logger.logrb(Level.INFO, "com.mycompany.mylib.Reader", "read",
 "log_messages", "reading_file", fileName);


By default, loggers send records to a ConsoleHandler that prints them to the System.err stream. Specifically, the logger sends the record to the parent handler, and the ultimate ancestor (with name "") has a ConsoleHandler. Like loggers, handlers have a logging level. For a record to be logged, its logging level must be above the threshold of both the logger and the handler. The log manager configuration file sets the logging level of the default console handler as


To log records with level FINE, change both the default logger level and the handler level in the configuration. Alternatively, you can bypass the configuration file altogether and install your own handler.

Logger logger = Logger.getLogger("com.mycompany.myapp");
Handler handler = new ConsoleHandler();

By default, a logger sends records both to its own handlers and the handlers of the parent. Our logger is a child of the primordial logger (with name "") that sends all records with level INFO or higher to the console. But we don't want to see those records twice. For that reason, we set the useParentHandlers property to false. To send log records elsewhere, add another handler. The logging API provides two useful handlers for this purpose, a FileHandler and a SocketHandler. The SocketHandler sends records to a specified host and port. Of greater interest is the FileHandler that collects records in a file. You can simply send records to a default file handler, like this:

FileHandler handler = new FileHandler();

The records are sent to a file javan.log in the user's home directory, where n is a number to make the file unique. If there is no concept of a user's home directory (for example, in Windows 95), then the file is stored in a default location such as C:\Windows. The records are formatted in XML. A typical log record has the form

 <message>Reading file corejava.gif</message>

You can modify the default behavior of the file handler by setting various parameters in the log manager configuration (see Table 11-2), or by using another constructor (see the API notes at the end of this section). You probably don't want to use the default log file name. Therefore, you should use another pattern, such as %h/myapp.log. (See Table 11-3 for an explanation of the pattern variables.) If multiple apps (or multiple copies of the same app) use the same log file, then you should turn the "append" flag on. Alternatively, use %u in the file name pattern so that each app creates a unique copy of the log. It is also a good idea to turn file rotation on. Log files are kept in a rotation sequence, such as myapp.log.0, myapp.log.1, myapp.log.2, and so on. Whenever a file exceeds the size limit, the oldest log is deleted, the other files are renamed, and a new file with generation number 0 is created.

Java graphics exclamatory_icon.gif

Many programmers use logging as an aid for the technical support staff. If a program misbehaves in the field, then the user can send back the log files for inspection. In that case, you should turn the "append" flag on, use rotating logs, or both.

Table 11-2. File handler configuration parameters

Configuration Property



java.util.logging. FileHandler.level

The handler level.


java.util.logging. FileHandler.append

Controls whether the handler should append to an existing file, or open a new file for each program run.


java.util.logging. FileHandler.limit

The approximate maximum number of bytes to write in a file before opening another. (0 = no limit).

0 (no limit) in the FileHandler class, 50000 in the default log manager configuration

java.util.logging. FileHandler.pattern

The pattern for the log file name. See Table 11-3 for pattern variables.


java.util.logging. FileHandler.count

The number of logs in a rotation sequence.

1 (no rotation)

java.util.logging. FileHandler.filter

The filter class to use.

No filtering

java.util.logging. FileHandler.encoding

The character encoding to use.

The platform encoding

java.util.logging. FileHandler.formatter

The record formatter.

java.util.logging. XMLFormatter

You can also define your own handlers, by overriding the Handler or the StreamHandler class. We define such a handler in the example program at the end of this section. That handler displays the records in a window (see Screenshot-3).
Screenshot-3. A log handler that displays records in a window

Java graphics 11fig03.gif

Table 11-3. Log file pattern variables




The value of the user.home system property.


The system temporary directory.


A unique number to resolve conflicts.


The generation number for rotated logs. (A .%g suffix is used if rotation is specified and the pattern doesn't contain %g.)


The % character.

The handler extends the StreamHandler class and installs a stream whose write methods display the stream output in a text area.
class WindowHandler extends StreamHandler
 public WindowHandler()
 . . .
 final JTextArea output = new JTextArea();
 public void write(int b)
 output.append("" + (char)b);
 public void write(byte[] b, int off, int len)
 output.append(new String(b, off, len));
 . . .

There is just one problem with this approach—the handler buffers records and only writes them to the stream when the buffer is full. Therefore, we override the publish method to flush the buffer after each record:

class WindowHandler extends StreamHandler
 . . .
 public void publish(LogRecord record)

If you want to write more exotic stream handlers, extend the Handler class and define the publish, flush, and close methods.


By default, records are filtered according to their logging levels. Each logger and handler can have an optional filter to perform added filtering. You define a filter by implementing the Filter interface and defining the method

boolean isLoggable(LogRecord record)

Analyze the log record, using any criteria that you desire, and return true for those records that should be included in the log. For example, a particular filter may only be interested in the messages generated by the entering and exiting methods. The filter should then call record.getMessage() and check whether it starts with ENTRY or RETURN. To install a filter into a logger or handler, simply call the setFilter method. Note that you can have at most one filter at a time.


The ConsoleHandler and FileHandler classes emit the log records in text and XML formats. However, you can define your own formats as well. You need to extend the Formatter class and override the method

String format(LogRecord record)

Format the information in the record in any way you like and return the resulting string. In your format method, you may want to call the method

String formatMessage(LogRecord record)

That method formats the message part of the record, substituting parameters and applying localization. Many file formats (such as XML) require a head and tail part that surrounds the formatted records. In that case, override the methods

String getHead(Handler h)
String getTail(Handler h)

Finally, call the setFormatter method to install the formatter into the handler. With so many options for logging, it is easy to lose track of the fundamentals. The "Logging Cookbook" sidebar summarizes the most common operations.

Logging Cookbook

  1. For a simple app, choose a single logger. It is a good idea to give the logger the same name as your main app package, such as com.mycompany.myprog. You can always get the logger by calling


    For convenience, you may want to add static fields

    private static final Logger logger
     = Logger.getLogger("com.mycompany.myprog");

    to classes with a lot of logging activity.

  2. The default logging configuration logs all messages of level INFO or higher to the console. Users can override the default configuration, but as you have seen, the process is a bit involved. Therefore, it is a good idea to install a more reasonable default in your app. The following code ensures that all messages are logged to an app-specific file. Place the into the main method of your app.

    if (System.getProperty("java.util.logging.config.class")
     == null
     && System.getProperty("java.util.logging.config.file")
     == null)
     final int LOG_ROTATION_COUNT = 10;
     Handler handler = new FileHandler("%h/myapp.log",
     catch (IOException exception)
     "Can't create log file handler", exception);

  3. Now you are ready to log to your heart's content. Keep in mind that all messages with level INFO, WARNING, and SEVERE show up on the console. Therefore, these levels should be reserved for messages that are meaningful to the users of your program. The level FINE is a good choice for logging messages that are intended for programmers. Whenever you are tempted to call System.out.println, emit a log message instead:

     File open dialog canceled");

    It is also a good idea to log unexpected exceptions, for example

     . . .
    catch (SomeException exception)
     Level.FINE, "explanation", exception);

Here is the code for the image viewer that logs events to a log window.
Example 11-4
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.awt.image.*;
 4. import*;
 5. import java.util.logging.*;
 6. import javax.swing.*;
 8. /**
 9. A modification of the image viewer program that logs
 10. various events.
 12. public class LoggingImageViewer
 13. {
 14. public static void main(String[] args)
 15. {
 17. if (System.getProperty(
 18. "java.util.logging.config.class") == null
 19. && System.getProperty(
 20. "java.util.logging.config.file") == null)
 21. {
 22. try
 23. {
 24. Logger.getLogger("").setLevel(Level.ALL);
 25. final int LOG_ROTATION_COUNT = 10;
 26. Handler handler = new FileHandler(
 27. "%h/LoggingImageViewer.log",
 29. Logger.getLogger("").addHandler(handler);
 30. }
 31. catch (IOException exception)
 32. {
 33. Logger.getLogger("com.horstmann.corejava").log(
 34. Level.SEVERE,
 35. "Can't create log file handler", exception);
 36. }
 37. }
 39. Handler windowHandler = new WindowHandler();
 40. windowHandler.setLevel(Level.ALL);
 41. Logger.getLogger("").addHandler(windowHandler);
 43. JFrame frame = new ImageViewerFrame();
 44. frame.setTitle("LoggingImageViewer");
 45. frame.setSize(300, 400);
 46. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 48. Logger.getLogger("com.horstmann.corejava").fine(
 49. "Showing frame");
 51. }
 52. }
 54. /**
 55. The frame that shows the image.
 56. */
 57. class ImageViewerFrame extends JFrame
 58. {
 59. public ImageViewerFrame()
 60. {
 61. logger.entering("ImageViewerFrame", "ImageViewerFrame");
 62. // set up menu bar
 63. JMenuBar menuBar = new JMenuBar();
 64. setJMenuBar(menuBar);
 66. JMenu menu = new JMenu("File");
 67. menuBar.add(menu);
 69. JMenuItem openItem = new JMenuItem("Open");
 70. menu.add(openItem);
 71. openItem.addActionListener(new FileOpenListener());
 73. JMenuItem exitItem = new JMenuItem("Exit");
 74. menu.add(exitItem);
 75. exitItem.addActionListener(new
 76. ActionListener()
 77. {
 78. public void actionPerformed(ActionEvent event)
 79. {
 80. logger.fine("Exiting.");
 81. System.exit(0);
 82. }
 83. });
 85. // use a label to display the images
 86. label = new JLabel();
 87. Container contentPane = getContentPane();
 88. contentPane.add(label);
 89. logger.exiting("ImageViewerFrame", "ImageViewerFrame");
 90. }
 92. private class FileOpenListener implements ActionListener
 93. {
 94. public void actionPerformed(ActionEvent evt)
 95. {
 96. logger.entering("ImageViewerFrame.FileOpenListener",
 97. "actionPerformed", evt);
 99. // set up file chooser
100. JFileChooser chooser = new JFileChooser();
101. chooser.setCurrentDirectory(new File("."));
103. // accept all files ending with .gif
104. chooser.setFileFilter(new
105. javax.swing.filechooser.FileFilter()
106. {
107. public boolean accept(File f)
108. {
109. return f.getName().toLowerCase()
110. .endsWith(".gif")
111. || f.isDirectory();
112. }
113. public String getDescription()
114. {
115. return "GIF Images";
116. }
117. });
119. // show file chooser dialog
120. int r = chooser.showOpenDialog(ImageViewerFrame.this);
122. // if image file accepted, set it as icon of the label
123. if(r == JFileChooser.APPROVE_OPTION)
124. {
125. String name
126. = chooser.getSelectedFile().getPath();
127. logger.log(Level.FINE, "Reading file {0}", name);
128. label.setIcon(new ImageIcon(name));
129. }
130. else
131. logger.fine("File open dialog canceled.");
132. logger.exiting("ImageViewerFrame.FileOpenListener",
133. "actionPerformed");
134. }
135. }
137. private JLabel label;
138. private static Logger logger
139. = Logger.getLogger("com.horstmann.corejava");
140. }
142. /**
143. A handler for displaying log records in a window.
144. */
145. class WindowHandler extends StreamHandler
146. {
147. public WindowHandler()
148. {
149. JFrame frame = new JFrame();
150. final JTextArea output = new JTextArea();
151. frame.setSize(200, 200);
152. frame.setContentPane(new JScrollPane(output));
154. setOutputStream(new
155. OutputStream()
156. {
157. public void write(int b)
158. {
159. output.append("" + (char)b);
160. }
161. public void write(byte[] b, int off, int len)
162. {
163. output.append(new String(b, off, len));
164. }
165. });
166. }
168. public void publish(LogRecord record)
169. {
170. super.publish(record);
171. flush();
172. }
173. }

java.util.logging.Logger 1.4

Java graphics api_icon.gif
  • Logger getLogger(String loggerName)
  • Logger getLogger(String loggerName, String bundleName)

    get the logger with the given name. If the logger doesn't exist, it is created.



    the hierarchical logger name, such as com.mycompany.myapp



    the name of the resource bundle for looking up localized messages

  • void severe(String message)
  • void warning(String message)
  • void info(String message)
  • void config(String message)
  • void fine(String message)
  • void finer(String message)
  • void finest(String message)

    log a record with the level indicated by the method name and the given message.

  • void entering(String className, String methodName)
  • void entering(String className, String methodName, Object param)
  • void entering(String className, String methodName, Object[] param)
  • void exiting(String className, String methodName)
  • void exiting(String className, String methodName, Object result)

    log a record that describes entering or exiting a method with the given parameter(s) or return value.

  • void throwing(String className, String methodName, Throwable t)

    logs a record that describes throwing of the given exception object.

  • void log(Level level, String message)
  • void log(Level level, String message, Object obj)
  • void log(Level level, String message, Object[] objs)
  • void log(Level level, String message, Throwable t)

    log a record with the given level and message, optionally including objects or a throwable. To include objects, the message must contain formatting placeholders {0}, {1} etc.

  • void logp(Level level, String className, String methodName, String message)
  • void logp(Level level, String className, String methodName, String message, Object obj)
  • void logp(Level level, String className, String methodName, String message, Object[] objs)
  • void logp(Level level, String className, String methodName, String message, Throwable t)

    log a record with the given level, precise caller information, and message, optionally including objects or a throwable.

  • void logrb(Level level, String className, String methodName, String bundleName, String message)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Object obj)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Object[] objs)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Throwable t)

    log a record with the given level, precise caller information, resource bundle name, and message, optionally including objects or a throwable.

  • Level getLevel()
  • void setLevel(Level l)

    get and set the level of this logger.

  • Logger getParent()
  • void setParent(Logger l)

    get and set the parent logger of this logger.

  • Handler[] getHandlers()

    gets all handlers of this logger.

  • void addHandler(Handler h)
  • void removeHandler(Handler h)

    add or remove a handler for this logger.

  • boolean getUseParentHandlers()
  • void setUseParentHandlers(boolean b)

    get and set the "use parent handler" property. If this property is true, the logger forwards all logged records to the handlers of its parent.

  • Filter getFilter()
  • void setFilter(Filter f)

    get and set the filter of this logger.

java.util.logging.Handler 1.4

Java graphics api_icon.gif
  • abstract void publish(LogRecord record)

    sends the record to the intended destination.

  • abstract void flush()

    flushes any buffered data.

  • abstract void close()

    flushes any buffered data and releases all associated resources.

  • Filter getFilter()
  • void setFilter(Filter f)

    get and set the filter of this handler.

  • Formatter getFormatter()
  • void setFormatter(Formatter f)

    get and set the formatter of this handler.

  • Level getLevel()
  • void setLevel(Level l)

    get and set the level of this handler.

java.util.logging.ConsoleHandler 1.4

Java graphics api_icon.gif
  • ConsoleHandler()

    constructs a new console handler.

java.util.logging.FileHandler 1.4

Java graphics api_icon.gif
  • FileHandler(String pattern)
  • FileHandler(String pattern, boolean append)
  • FileHandler(String pattern, int limit, int count)
  • FileHandler(String pattern, int limit, int count, boolean append)

    construct a file handler.



    The pattern for constructing the log file name. See Table 11-3 for pattern variables.



    The approximate maximum number of bytes before a new log file is opened.



    The number of files in a rotation sequence.



    True if a newly constructed file handler object should append to an existing log file.

java.util.logging.LogRecord 1.4

Java graphics api_icon.gif
  • Level getLevel()

    gets the logging level of this record.

  • String getLoggerName()

    gets the name of the logger that is logging this record.

  • ResourceBundle getResourceBundle()
  • String getResourceBundleName()

    get the resource bundle, or its name, to be used for localizing the message, or null if none is provided.

  • String getMessage()

    gets the "raw" message, before localization or formatting.

  • Object[] getParameters()

    gets the parameter objects, or null if none is provided.

  • Throwable getThrown()

    gets the thrown object, or null if none is provided.

  • String getSourceClassName()
  • String getSourceMethodName()

    get the location of the code that logged this record. This information may be supplied by the logging code, or automatically inferred from the runtime stack. It might be inaccurate, if the logging code supplied the wrong value, or if the running code was optimized and the exact location cannot be inferred.

  • long getMillis()

    gets the creation time, in milliseconds, since 1970.

  • long getSequenceNumber()

    gets the unique sequence number of this record.

  • int getThreadID()

    gets the unique ID for the thread in which this record was created. These IDs are assigned by the LogRecord class and have no relationship to other thread IDs.

java.util.logging.Filter 1.4

Java graphics api_icon.gif
  • boolean isLoggable(LogRecord record)

    returns true if the given log record should be logged.

java.util.logging.Formatter 1.4

Java graphics api_icon.gif
  • abstract String format(LogRecord record)

    returns the string that results from formatting the given log record.

  • String getHead(Handler h)
  • String getTail(Handler h)

    return the strings that should appear at the head and tail of the document containing the log records. The Formatter superclass defines these methods to return the empty string; override them if necessary.

  • String format(LogRecord record)

    returns the localized and formatted message part of the log record.

Java ScreenShot