Tuesday, 9 June 2009

Getting Started with java.util.logging.Logger

The basic method of logging would be to open a file and write your data to it. Not with Java! The Logger has some niffty features and is even easier than writing to a file.

Loggers main offering is a level that can be set, anything at or above that level gets output, anything below gets silently ignored. So you can keep your debug messages in your code and only turn them on when needed.

The logging levels are:

SEVEREThe highest value; intended for extremely important messages (e.g. fatal program errors).
WARNINGIntended for warning messages.
INFOInformational runtime messages.
CONFIGInformational messages about configuration settings/setup.
FINEUsed for greater detail, when debugging/diagnosing problems.
FINEREven greater detail.
FINESTThe lowest value; greatest detail.

A quick start example would look something like this:

package com.wownow;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyLoggingTest {

public static void main(String[] args) throws IOException {

Level logLevel = Level.FINE;

FileHandler fh = new FileHandler("MyLogFile.xml");

Logger logger = Logger.getLogger("MyLogger");

logger.severe("My Severe Message");
logger.warning("My Warning Message");
logger.info("My Info Message");
logger.config("My Config Message");
logger.fine("My Fine Message");
logger.finer("My Finer Message");
logger.finest("My Finest Message");




In this example we:

  • first set the logLevel to "FINE",

  • then create our log file "MyLogFile.xml", by default Logger outputs to file in xml format.

  • We then create the logger object, set the level and add the file handler.

  • Next we output a message for each logging level. Only the messages above the set level, "FINE", will be output. The logger also outputs to console but only to "INFO" level by default.

  • We then close the file handler.

The xml output looks something like:

<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<message>My Severe Message</message>
<message>My Warning Message</message>

There are also two special levels Level.ALL and Level.OFF

See Console,Text and XML Logger Output to see how to output different levels and formats to different destinations.

There is much more to Logger, see here.


No comments: