7.10. Using an Abstract Logging Interface
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.
Solution
Write messages to the Jakarta 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
.
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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.