Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

7.10. Using an Abstract Logging Interface

7.10.1. Problem

You are writing a reusable library, and you do not know where or how your code will execute. You need to write log messages to an abstracted logging interface because you cannot count on the presence of Log4J or JDK 1.4 logging.

7.10.2. Solution

Write messages to the Commons Logging Log interface, and rely on Commons Logging to decide which concrete logging framework to use at runtime. The following code uses the Log interface to log trace, debug, info, warning, error, and fatal messages:

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log
Log log = LogFactory.getLog( "com.discursive.jccook.SomeApp" ); 
if( log.isTraceEnabled( ) ) {
    log.trace( "This is a trace message" );
}
if( log.isDebugEnabled( ) ) {
    log.debug( "This is a debug message" );
}
log.info( "This is an informational message" );
log.warn( "This is a warning" );
log.error( "This is an error" );
log.fatal( "This is fatal" );

LogFactory.getInstance( ) returns an implementation of the Log interface, which corresponds to an underlying concrete logging framework. For example, if your system is configured to use Apache Log4J, a Log4JLogger is returned, which corresponds to the Log4J category com.discursive.jccook.SomeApp.

7.10.3. Discussion

The developers of a reusable library can rarely predict where and when such a library will be used, and since there are a number of logging frameworks currently available, it makes sense to use Commons Logging when developing reusable components such as Commons components. When LogFactory.getInstance() is called, Commons Logging takes care of locating and managing the appropriate logging framework by testing a number of system properties and libraries available on the classpath. For the developer of a small reusable component, the complexity ends at the calls to the Log interface; the burden of configuring the underlying logging framework is shifted to the developer integrating this library into a larger system.

7.10.4. See Also

Recipe 7.11 details the algorithm Commons Logging uses to identify the appropriate concrete logging framework to use at runtime.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.