or years, "System.out.println
" seemed to be the only choice Java developers had for logging; there was no standard logging API in the Java SDK and no widely accepted third-party logging API. However, Java developers looking for a better way to do logging will be cheered by the recent release of the J2SE 1.4 logging API.
J2SE 1.4 offers a simple yet flexible logging framework that Java developers can customize for their application logging needs. Figure 1
shows the basic logging process and the J2SE classes involved.
Logger is the primary interface for a Java logging application and in most cases it will be the only class an application developer has to deal with. Every log request is made through a Logger object, which maintains the same namespace hierarchy as a regular Java object. A logger of the child namespace will inherit all the logging properties from a logger of its parent namespace. For instance, a logger of namespace "com.foo.bar" will have the same logging level, handler, and formatter as the logger of namespace "com.foo."
LogRecord is the internal representation of a log request that is used within the logging framework. Most application developers will not deal with this class directly. LogRecord implements the Java Seriliazable interface.
The Handler object takes a LogRecord from Logger and publishes it to the external medium. The Handler implementations that come with J2SE can publish LogRecord to System.err, OutputStream, disk file, etc.
Some classes of the J2SE logging API are not shown in Figure 1, such as Formatter, which is used to format each LogRecord in the application-specific form or locale. In addition, Level is used to specify the log level at which a log request should be made. It also implements the Java Serializable interface.
|Figure 1: This architectural diagram shows the basic logging process and the J2SE classes involved.|
The default implementation of the J2SE logging API may be sufficient for the logging needs of most Java applications. But what if you are logging under a distributed and multithreaded environment? In these situations, you'll have to answer the following questions:
- Where should I store the logslocally or on a centralized network server?
- How should my application access logs from different machines in the network?
- How do I control log levels remotely at runtime to increase or decrease the number of log requests?
- Should I log by package/class like the J2SE logging API does, or should I make logs based on a disparate Java thread?
In this article, I'll show you how to build a logging framework for a distributed and multithreaded Java application.