Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Log4j delivers control over logging - JavaWorld November 2000

Log4j delivers control over logging - JavaWorld November 2000

Tutorial Details:

Log4j delivers control over logging
Log4j delivers control over logging
By: By Ceki Gülcü
The open source log4j API for Java offers fast, efficient log services
lmost every large application includes its own logging or tracing API. Experience indicates that logging represents an important component of the development cycle. As such, logging offers several advantages. First, it can provide precise context about a run of the application. Once inserted into the code, the generation of logging output requires no human intervention. Second, log output can be saved in a persistent medium to be studied at a later time. Finally, in addition to its use in the development cycle, a sufficiently rich logging package can also be employed as an audit tool.
In conformance with that rule, in early 1996 the EU SEMPER (Secure Electronic Marketplace for Europe) project decided to write its own tracing API. After countless enhancements, several incarnations, and much work, that API has evolved into log4j, a popular logging package for Java. The package is distributed under the IBM Public License, certified by the open source initiative.
Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate those concerns, log4j is designed to be fast and flexible. Since logging is rarely the main focus of an application, log4j API strives to be simple to understand and use.
This article starts by describing the main components of the log4j architecture. It proceeds with a simple example depicting basic usage and configuration. It wraps up by touching on performance issues and the upcoming logging API from Sun.
Categories, appenders, and layouts
Log4j has three main components:
Categories
Appenders
Layouts
The three components work together to enable developers to log messages according to message type and priority, and to control at runtime how these messages are formatted and where they are reported. Let's look at each in turn.
Category hierarchy
The first and foremost advantage of any logging API over plain System.out.println resides in its ability to disable certain log statements while allowing others to print unhindered. That capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria.
In conformance with that observation, the org.log4j.Category class figures at the core of the package. Categories are named entities. In a naming scheme familiar to Java developers, a category is said to be a parent of another category if its name, followed by a dot, is a prefix of the child category name. For example, the category named com.foo is a parent of the category named com.foo.Bar . Similarly, java is a parent of java.util and an ancestor of java.util.Vector .
The root category, residing at the top of the category hierarchy, is exceptional in two ways:
It always exists
It cannot be retrieved by name
In the Category class, invoking the static getRoot() method retrieves the root category. The static getInstance() method instantiates all other categories. getInstance() takes the name of the desired category as a parameter. Some of the basic methods in the Category class are listed below:
package org.log4j;
public Category class {
// Creation & retrieval methods:
public static Category getRoot();
public static Category getInstance(String name);
// printing methods:
public void debug(String message);
public void info(String message);
public void warn(String message);
public void error(String message);
// generic printing method:
public void log(Priority p, String message);
}
Categories may be assigned priorities from the set defined by the org.log4j.Priority class. Although the priority set matches that of the Unix Syslog system, log4j encourages the use of only four priorities: ERROR, WARN, INFO and DEBUG, listed in decreasing order of priority. The rationale behind that seemingly restricted set is to promote a more flexible category hierarchy rather than a static (even if large) set of priorities. You may, however, define your own priorities by subclassing the Priority class. If a given category does not have an assigned priority, it inherits one from its closest ancestor with an assigned priority. As such, to ensure that all categories can eventually inherit a priority, the root category always has an assigned priority.
To make logging requests, invoke one of the printing methods of a category instance. Those printing methods are:
error()
warn()
info()
debug()
log()
By definition, the printing method determines the priority of a logging request. For example, if c is a category instance, then the statement c.info("..") is a logging request of priority INFO.
A logging request is said to be enabled if its priority is higher than or equal to the priority of its category. Otherwise, the request is said to be disabled. . A category without an assigned priority will inherit one from the hierarchy.
Below, you'll find an example of that rule:
// get a category instance named "com.foo"
Category cat = Category.getInstance( "com.foo" );
// Now set its priority.
cat .setPriority( Priority.INFO );
Category barcat = Category.getInstance( "com.foo.Bar" );
// This request is enabled, because WARN >= INFO .
cat. warn ("Low fuel level.");
// This request is disabled, because DEBUG < INFO .
cat. debug ("Starting search for nearest gas station.");
// The category instance barcat, named "com.foo.Bar",
// will inherit its priority from the category named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO .
barcat. info ("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO .
barcat. debug ("Exiting gas station search");
Calling the getInstance() method with the same name will always return a reference to the exact same category object. Thus, it is possible to configure a category and then retrieve the same instance somewhere else in the code without passing around references. Categories can be created and configured in any order. In particular, a parent category will find and link to its children even if it is instantiated after them. The log4j environment typically configures at application initialization, preferably by reading a configuration file, an approach we'll discuss shortly.
Log4j makes it easy to name categories by software component. That can be accomplished by statically instantiating a category in each class, with the category name equal to the fully qualified name of the class -- a useful and straightforward method of defining categories. As the log output bears the name of the generating category, such a naming strategy facilitiates identifying a log message's origin. However, that is only one possible, albeit common, strategy for naming categories. Log4j does not restrict the possible set of categories. Indeed, the developer is free to name the categories as desired.
Appenders and layouts
The ability to selectively enable or disable logging requests based on their category is only part of the picture. Log4j also allows logging requests to print to multiple output destinations called appenders in log4j speak. Currently, appenders exist for the console, files, GUI components, remote socket servers, NT Event Loggers, and remote UNIX Syslog daemons.
A category may refer to multiple appenders. Each enabled logging request for a given category will be forwarded to all the appenders in that category as well as the appenders higher in the hierarchy. In other words, appenders are inherited additively from the category hierarchy. For example, if you add a console appender to the root category, all enabled logging requests will at least print on the console. If, in addition, a file appender is added to a category, say C , then enabled logging requests for C and C' s children will print on a file and on the console. Be aware that you can override that default behavior so that appender accumulation is no longer additive.
More often than not, users want to customize not only the output destination but also the output format, a feat accomplished by associating a layout with an appender. The layout formats the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination. The PatternLayout , part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.
For example, the PatternLayout with the conversion pattern %r [%t]%-5p %c - %m%n will output something akin to:
176 [main] INFO org.foo.Bar - Located nearest gas station.
In the output above:
The first field equals the number of milliseconds elapsed since the start of the program
The second field indicates the thread making the log request
The third field represents the priority of the log statement
The fourth field equals the name of the category associated with the log request
The text after the - indicates the statement's message.
Configuration
Inserting log requests into the application code requires a fair amount of planning and effort. Observation shows that code dedicated to logging represents approximately four percent of the application's total. Consequently, even moderately sized applications will have thousands of logging statements embedded within their code. Given their number, it becomes imperative to manage those log statements without the need to modify them manually.
The log4j environment can be fully configured programmatically. However, it is far more flexible to configure log4j by using configuration files. Currently, configuration files can be written in XML or in Java properties (key=value) format.
Let us give a taste of how that is done with the help of an imaginary application -- MyApp -- that uses log4j:
import com.foo.Bar;
// Import log4j c


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Log4j delivers control over logging - JavaWorld November 2000

View Tutorial:
Log4j delivers control over logging - JavaWorld November 2000

Related Tutorials:

Accelerate your RMI programming
Accelerate your RMI programming
 
I want my AOP!, Part 1
I want my AOP!, Part 1
 
Transaction and redelivery in JMS
Transaction and redelivery in JMS
 
I want my AOP!, Part 3
I want my AOP!, Part 3
 
Jtrix: Web services beyond SOAP
Jtrix: Web services beyond SOAP
 
Create your own type 3 JDBC driver, Part 2
Create your own type 3 JDBC driver, Part 2
 
J2SE 1.4 breathes new life into the CORBA community, Part 1
J2SE 1.4 breathes new life into the CORBA community, Part 1
 
A first look at JavaServer Faces, Part I
A first look at JavaServer Faces, Part Learn how to implement Web-based user interfaces with JSF
 
Simply Singleton
Simply Singleton
 
Create client-side user interfaces in HTML, Part 2
Create client-side user interfaces in HTML, Part 2
 
To my mind, of few interest
To my mind, of few interest
 
Tracing in a multithreaded, multiplatform environment
Tracing in a multithreaded, multiplatform environment In \"Use a consistent trace system for easier debugging,\" Scott Clee showed you how to trace and log from a custom class to provide a consistent tracing approach across your applications. This approa
 
Ganymede
A log4j plugin to Eclipse that works similar to chainsaw (SocketServer). Includes color, filtering, detailed information, and saves settings.
 
FindBugs, Part 2: Writing custom detectors
FindBugs, Part 2: Writing custom detectors How to write custom detectors to find application-specific problems In the first article in this series, I showed you how to set up and execute FindBugs. Now we'll take a look at FindBugs' most powerful fea
 
Reporting Application Errors by Email
Reporting Application Errors by Email It is common practice for server-side applications to log messages to files on the server's file system. These logs are a vital source of information for system administrators and the application development team. If
 
JTimepiece
JTimepiece is the advanced library for working with dates and times in Java. Many easy-to-use methods in this API make it easy for any developer, from beginner to expert, to use JTimepiece.
 
Write custom appenders for log4j
The Apache Software Foundation's log4j logging library is one of the better logging systems around. It's both easier to use and more flexible than Java's built-in logging system.
 
one-jar
One-JAR is a simple solution to a vexing problem in Java: how to distribute an application as a single jar-file, when it depends on multiple other jar-files. One-JAR uses a custom classloader to discover library jar files inside the main jar.
 
New Technical Articles: 64-bit Programming on Solaris 10 OS for x86 Platforms
Four technical articles describe the new Sun Studio 10 software's 64-bit programming features on the Solaris 10 OS for x86 and AMD64 platforms. Important issues regarding the AMD64 ABI (Application Binary Interface), debugging, migration to 64-bits, and p
 
Sun Java Desktop System Now Supports Solaris 10 OS
Sun Java Desktop System, Release 3 is now available on the Solaris 10 OS, along with management tools and some free and trial development tools.
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.