Package java.util.logging Description (from sun)Package java.util.logging provides the classes and interfaces of the JavaTM 2 platform's core logging facilities. The central goal of the logging APIs is to support maintaining and servicing software at customer sites. There are four main target uses of the logs: - Problem diagnosis by end users and system administrators. This consists of simple logging of common problems that can be fixed or tracked locally, such as running out of resources, security failures, and simple configuration errors.
- Problem diagnosis by field service engineers. The logging information used by field service engineers may be considerably more complex and verbose than that required by system administrators. Typically such information will require extra logging within particular subsystems.
- Problem diagnosis by the development organization. When a problem occurs in the field, it may be necessary to return the captured logging information to the original development team for diagnosis. This logging information may be extremely detailed and fairly inscrutable. Such information might include detailed tracing on the internal execution of particular subsystems.
- Problem diagnosis by developers. The Logging APIs may also be used to help debug an application under development. This may include logging information generated by the target application as well as logging information generated by lower-level libraries. Note however that while this use is perfectly reasonable, the logging APIs are not intended to replace the normal debugging and profiling tools that may already exist in the development environment.
The key elements of this package include: - Logger: The main entity on which applications make logging calls. A Logger object is used to log messages for a specific system or application component.
- LogRecord: Used to pass logging requests between the logging framework and individual log handlers.
- Handler: Exports LogRecord objects to a variety of destinations including memory, output streams, consoles, files, and sockets. A variety of Handler subclasses exist for this purpose. Additional Handlers may be developed by third parties and delivered on top of the core platform.
- Level: Defines a set of standard logging levels that can be used to control logging output. Programs can be configured to output logging for some levels while ignoring output for others.
- Filter: Provides fine-grained control over what gets logged, beyond the control provided by log levels. The logging APIs support a general-purpose filter mechanism that allows application code to attach arbitrary filters to control logging output.
- Formatter: Provides support for formatting LogRecord objects. This package includes two formatters, SimpleFormatter and XMLFormatter, for formatting log records in plain text or XML respectively. As with Handlers, additional Formatters may be developed by third parties.
The Logging APIs offer both static and dynamic configuration control. Static control enables field service staff to set up a particular configuration and then re-launch the application with the new logging settings. Dynamic control allows for updates to the logging configuration within a currently running program. The APIs also allow for logging to be enabled or disabled for different functional areas of the system. For example, a field service engineer might be interested in tracing all AWT events, but might have no interest in socket events or memory management.
java.util.logging MemoryHandler A MemoryHandler stores LogRecord objects in a fixed-sized buffer in memory. When the buffer fills up, it discards the oldest record one each time a new record arrives. It maintains a reference to another Handler object, and whenever the push( ) method is called, or whenver a LogRecord arrives with a level at or higher than the pushLevel threshold, it "pushes" all of buffered LogRecord objects to that other Handler object, which typically formats and outputs them to some appropriate destination. Because MemoryHandler never outputs log records itself, it does not use the formatter or encoding properties inherited from its superclass. See Handler details. Property or argument LogManager property name Default level java.util.logging.MemoryHandler.level Level.ALL filter java.util.logging.MemoryHandler.filter null target java.util.logging.MemoryHandler.target no default size java.util.logging.MemoryHandler.size 1000 log records pushLevel ava.util.logging.MemoryHandler.push Level.SEVERE
Java logging Control FlowApplications make logging calls on Logger objects. Loggers are organized in a hierarchical namespace and child Loggers may inherit some logging properties from their parents in the namespace. Applications make logging calls on Logger objects. These Logger objects allocate LogRecord objects which are passed to Handler objects for publication. Both Loggers and Handlers may use logging Levels and (optionally) Filters to decide if they are interested in a particular LogRecord. When it is necessary to publish a LogRecord externally, a Handler can (optionally) use a Formatter to localize and format the message before publishing it to an I/O stream.See below figure  Examples of java loggingThe following is a small program that performs logging using the default configuration. This program relies on the root handlers that were established by the LogManager based on the configuration file. It creates its own Logger object and then makes calls to that Logger object to report various events. package biz.hotdir; import java.util.logging.*; public class Loggingemo{ // Obtain a suitable logger. private static Logger logger = Logger.getLogger("biz.hotdir.loggingemo"); public static void main(String argv[]){ // Log a few message at different severity levels 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"); } }
Java Logging a Method CallThe logger provides convenience methods Logger.entering() and Logger.exiting() for logging method calls. This example implements a method that logs the parameters upon entry and the result when returning.
package biz.hotdir; import java.util.logging.*; class LoggingDemo { public boolean myMethod(int p1, Object p2) { // Log entry Logger logger = Logger.getLogger("biz.hotdir.LoggingDemo"); if (logger.isLoggable(Level.FINER)) { logger.entering(this.getClass().getName(), "myMethod", new Object[]{new Integer(p1), p2}); } // Method body // Log exit boolean result = true; if (logger.isLoggable(Level.FINER)) { logger.exiting(this.getClass().getName(), "myMethod", new Boolean(result)); // Use the following if the method does not return a value logger.exiting(this.getClass().getName(), "myMethod"); } return result; } } Java Logging an ExceptionThe logger method log() can be used to log an exception. Also, the convenience method Logger.throwing() can be used by a method about to throw an exception. package biz.hotdir; import java.util.logging.*; class LoggingDemo { public void logMethod() { Logger logger = Logger.getLogger("biz.hotdir.LoggingDemo"); try { throw new IOException(); } catch (Throwable error){ logger.log(Level.SEVERE, "Uncaught exception", error); } Exception e = new IllegalStateException(); logger.throwing(this.getClass().getName(), "logMethod", e); } } Java Logging: Writing Log Records to a Log FileTo make a logger write log records to a file, you need to add a FileHandlerto the logger. See FileHandler description public FileHandler(String pattern, int limit, int count, boolean append) throws IOException, SecurityExceptionInitialize a FileHandler to write to a set of files with optional append. When (approximately) the given limit has been written to one file, another file will be opened. The output will cycle through a set of count files. The FileHandler is configured based on LogManager properties (or their default values) except that the given pattern argument is used as the filename pattern, the file limit is set to the limit argument, and the file count is set to the given count argument, and the append mode is set to the given append argument. The count must be at least 1. Parameters: pattern - the pattern for naming the output file limit - the maximum number of bytes to write to any one file count - the number of files to use append - specifies append mode Sample of Writing Log Records to a Log File try { // Create a file handler that write log record to a file called demo.log FileHandler handler = new FileHandler("demo.log"); Logger logger = Logger.getLogger("biz.hotdir"); logger.addHandler(handler); } catch (IOException e) { } Second Part Log4j tutorialOverview of log4jlog4j is the open source logging tool developed under the Jakarta Apache project. It is a set of APIs that allows developers to write log statements in their code and configure them externally, using properties files. Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported. The log4j API is very similar with Logging API. As a result of our campaign to influence and improve the JSR47 API, the final version of JSR47 resembles log4j very closely. There are two critical differences between the APIs. First, JSR47 requires JDK 1.4 whereas log4j is compatible with JDK 1.1 and later. Second, log4j offers much more functionality. It supports a rich configuration language, at least a dozen appenders and layouts as well as many other useful features. Installing Log4jThe latest version of log4j can be downloaded from http://jakarta.apache.org/log4j/docs/download.html Releases are available in two formats: zip and tar.gz. After unpacking the distribution, you should see the file LOG4J_HOME/dist/lib/log4j-VERSION.jar where LOG4J_HOME is the directory where you unpacked the log4j distribution and VERSION is the version of the log4j distribution you downloaded. To start using log4j simply add this jar file to your CLASSPATH. Very simple Log4j Examplepackage biz.hotdir; import org.apache.log4j.Logger; public class Log4jDemo { static Logger logger = Logger.getLogger("biz.hotdir.Log4jDemo"); static public void main(String[] args) { logger.debug("Hello Log4j."); } } |