provided by: 
Originally published at Internet.com
Logging provides a way to capture information about the operation of an application. Once captured, the information can be used for many purposes, but it is particularly useful for debugging, troubleshooting, and auditing. This article takes a look at logging in Java applications, presenting information on logging software, benefits, costs, and basic techniques.
LOGGING SOFTWARE
There are many logging packages available for Java applications. Here are a few:
* Java Logging API - Part of Java 2 Standard Edition Version 1.4. The Java Logging API supports dynamic configuration, hierachical loggers, multiple logging levels, and multiple output formats (plain text and XML).
* Log4j - An open source logging framework from the Apache Jakarta project. Log4j supports dynamic configuration, hierarchical loggers, multiple logging levels, and multiple output formats (plain text, HTML, XML, Unix syslog, Windows NT Event Log, and others). It was designed and built with an emphasis on speed and has been ported to C, C++, C#, Ruby, and Eiffel.
* Logging Toolkit for Java - A logging framework from the IBM alphaWorks project. Logging Toolkit for Java supports multiple loggers, filters, handlers, formatters, and multiple output devices.
* Protomatter Syslog - A logging framework that is part of Protomatter, an open source collection of Java utility classes. Syslog is roughly based on the Unix syslog facility and supports channels, multiple levels, and BEA WebLogic. It is also compatible with the Java Logging API.
* Java Logging Framework - A simple logging framework from The Object Guy. Java Logging Framework supports multiple loggers, filters, message formatting, and multiple output devices.
EVALUATING A LOGGING PACKAGE
Configuration:
* How is logging configured, programmatically or with a configuration file? The latter is better, because you don't have to write or change code to change the configuration.
* Is dynamic configuration supported? Dynamic configuration is better than static configuration, because configuration changes can take effect without restarting the application.
Loggers:
* Does the package support multiple loggers? For example, can you have one logger for database messages and one logger for GUI messages? Having multiple loggers makes logging more flexible, particularly for large systems.
* Does the package support heirachical loggers? This capability allows logging at arbitrarily fine granularity with ease of configuration.
Levels:
* Does the package support multiple logging levels, e.g. DEBUG, WARN, ERROR? Having multiple levels provides a mechanism for controlling the level of detail that is captured. For example, if DEBUG is more detailed than ERROR, and you configure the package to output only ERROR messages, DEBUG messages will not be captured.
Filters:
* Does the package support filters? Using either levels or arbitrary categories, filters provide a way to control which messages go to which output devices.
Output Formatting:
* What output formats does the package support? Plain text is the most general purpose format, but XML, HTML, and Unix syslog format can be useful.
* Does the package support message formatting (layout)? Being able to specify the layout of log messages - date/time format, fields shown, etc. - can make logs more readable.
Output Devices:
* Does the package support multiple output devices? Minimally, the package should support output to files, but output to the console, sockets, JMS, and email can be useful.
Speed:
* Is the package fast? Logging adds overhead to an application, so speed is important.
LOGGING BENEFITS
Here are some of the benefits of using logging in an application: * Logging can generate detailed information about the operation of an application.
* Once added to an application, logging requires no human intervention.
* Application logs can be saved and studied at a later time.
* If sufficiently detailed and properly formatted, application logs can provide audit trails.
* By capturing errors that may not be reported to users, logging can help support staff with troubleshooting.
* By capturing very detailed and programmer-specified messages, logging can help programmers with debugging.
* Logging can be a debugging tool where debuggers are not available, which is often the case with multi-threaded or distributed applications.
* Logging stays with the application and can be used anytime the application is run.
LOGGING COSTS
Logging is beneficial, but it does not come without costs: * Logging adds runtime overhead, from generating log messages and from device I/O.
* Logging adds programming overhead, because extra code has to be written to generate the log messages.
* Logging increases the size of code.
* If logs are too verbose or badly formatted, extracting information from them can be difficult.
* Logging statements can decrease the legibility of code.
* If log messages are not maintained with the surrounding code, they can cause confusion and can become a maintenance issue. (I have seen code with log messages that had no relation to what the code was doing. It was very confusing.)
* If not added during initial development, adding logging can require a lot of work modifying code.
SIMPLE LOGGING
Here is a fragment of code that illustrates simple logging using the Java Logging API: Logger logger = Logger.getLogger("org.foo"); // ... try { FileInputStream fis = new FileInputStream("foo.txt"); logger.fine("Input file 'foo.txt' opened."); try { while (true) { // ... if (c == null) { logger.fine("EOF encountered."); break; } } } finally { fis.close(); logger.fine("Input file closed."); } } catch(IOException ex) { logger.severe(ex.toString()); }
ENABLED CHECK
If your logging package supports it, check to see if logging is enabled before logging a message. Even though checking incurs the overhead of a method call, it will eliminate the cost of constructing the message if logging is not enabled. Here is an example using Log4j: Logger logger = Logger.getLogger("com.foo"); // ... if (logger.isDebugEnabled()) { logger.debug("Read " + byteCount + " bytes from file '" + filename + "'."); }
QUICK AND DIRTY LOGGER
If you cannot find a logging package that meets your needs, or just do not have time to look for one (been there), you can always build something quick and dirty, just to get basic logging functionality. An example of such a utility class is
Logger
This code will allow you to build your own logger if you cannot find a logging package that meets your needs, or just do not have time to look for one (been there), you can always build something quick and dirty, just to get basic logging functionality. It supports output to a text file, enabling/disabling logging, enabled checking, and nothing else. import java.io.*; import java.text.*; import java.util.*; /** * Logger is a quick and dirty logging class. It supports output to a text file, * logging on/off, enabled checking, and nothing else. */ public abstract class Logger { /** On/off flag. */ private static boolean on = true; /** Date format. */ private static SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy.dd.MM HH:mm"); /** * Return true if logging is on. */ public static boolean isOn() { return on; } /** * Set logging on/off. */ public static void setOn(boolean isOn) { on = isOn; } /** * Log the given message. */ public static void log(String msg) { if (on) { try { PrintStream logFile = new PrintStream( new FileOutputStream("log.txt", true)); try { logFile.println(dateFormat.format(new Date()) + " " + msg); } finally { logFile.close(); } } catch(IOException ex) { ex.printStackTrace(); } } } //-------------------------------------- /** * Test the Logger. */ public static void main(String[] args) { Logger.log("Test started."); Logger.log("Logging disabled after this."); Logger.setOn(false); Logger.log("This message should not be in the log."); Logger.setOn(true); Logger.log("Logging enabled."); Logger.log("Test completed."); } }
Return to article
Author: Thornton Rose
Read article at Internet.com site