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.
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
.
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 Jakarta 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.
Recipe 7.11 details the algorithm Commons Logging uses to identify the appropriate concrete logging framework to use at runtime.
18.216.47.169