org.apache.commons.logging

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Natural Language Processing
51.Net
52.Parser
53.PDF
54.Portal
55.Profiler
56.Project Management
57.Report
58.RSS RDF
59.Rule Engine
60.Science
61.Scripting
62.Search Engine
63.Security
64.Sevlet Container
65.Source Control
66.Swing Library
67.Template Engine
68.Test Coverage
69.Testing
70.UML
71.Web Crawler
72.Web Framework
73.Web Mail
74.Web Server
75.Web Services
76.Web Services apache cxf 2.2.6
77.Web Services AXIS2
78.Wiki Engine
79.Workflow Engines
80.XML
81.XML UI
Java Source Code / Java Documentation  » Library » apache commons logging 1.1.1 » org.apache.commons.logging 
org.apache.commons.logging

Simple wrapper API around multiple logging APIs.

Overview

This package provides an API for logging in server-based applications that can be used around a variety of different logging implementations, including prebuilt support for the following:

  • Log4J (version 1.2 or later) from Apache's Logging project. Each named Log instance is connected to a corresponding Log4J Logger.
  • JDK Logging API, included in JDK 1.4 or later systems. Each named Log instance is connected to a corresponding java.util.logging.Logger instance.
  • LogKit from Apache's Avalon project. Each named Log instance is connected to a corresponding LogKit Logger.
  • NoOpLog implementation that simply swallows all log output, for all named Log instances.
  • SimpleLog implementation that writes all log output, for all named Log instances, to System.err.

Quick Start Guide

For those impatient to just get on with it, the following example illustrates the typical declaration and use of a logger that is named (by convention) after the calling class:

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class Foo {

        private Log log = LogFactory.getLog(Foo.class);

        public void foo() {
            ...
            try {
                if (log.isDebugEnabled()) {
                    log.debug("About to do something to object " + name);
                }
                name.bar();
            } catch (IllegalStateException e) {
                log.error("Something bad happened to " + name, e);
            }
            ...
        }

Unless you configure things differently, all log output will be written to System.err. Therefore, you really will want to review the remainder of this page in order to understand how to configure logging for your application.

Configuring the Commons Logging Package

Choosing a LogFactory Implementation

From an application perspective, the first requirement is to retrieve an object reference to the LogFactory instance that will be used to create Log instances for this application. This is normally accomplished by calling the static getFactory() method. This method implements the following discovery algorithm to select the name of the LogFactory implementation class this application wants to use:

  • Check for a system property named org.apache.commons.logging.LogFactory.
  • Use the JDK 1.3 JAR Services Discovery mechanism (see http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html for more information) to look for a resource named META-INF/services/org.apache.commons.logging.LogFactory whose first line is assumed to contain the desired class name.
  • Look for a properties file named commons-logging.properties visible in the application class path, with a property named org.apache.commons.logging.LogFactory defining the desired implementation class name.
  • Fall back to a default implementation, which is described further below.

If a commons-logging.properties file is found, all of the properties defined there are also used to set configuration attributes on the instantiated LogFactory instance.

Once an implementation class name is selected, the corresponding class is loaded from the current Thread context class loader (if there is one), or from the class loader that loaded the LogFactory class itself otherwise. This allows a copy of commons-logging.jar to be shared in a multiple class loader environment (such as a servlet container), but still allow each web application to provide its own LogFactory implementation, if it so desires. An instance of this class will then be created, and cached per class loader.

The Default LogFactory Implementation

The Logging Package APIs include a default LogFactory implementation class ( org.apache.commons.logging.impl.LogFactoryImpl) that is selected if no other implementation class name can be discovered. Its primary purpose is to create (as necessary) and return Log instances in response to calls to the getInstance() method. The default implementation uses the following rules:

  • At most one Log instance of the same name will be created. Subsequent getInstance() calls to the same LogFactory instance, with the same name or Class parameter, will return the same Log instance.
  • When a new Log instance must be created, the default LogFactory implementation uses the following discovery process:
    • Look for a configuration attribute of this factory named org.apache.commons.logging.Log (for backwards compatibility to pre-1.0 versions of this API, an attribute org.apache.commons.logging.log is also consulted).
    • Look for a system property named org.apache.commons.logging.Log (for backwards compatibility to pre-1.0 versions of this API, a system property org.apache.commons.logging.log is also consulted).
    • If the Log4J logging system is available in the application class path, use the corresponding wrapper class (Log4JLogger).
    • If the application is executing on a JDK 1.4 system, use the corresponding wrapper class (Jdk14Logger).
    • Fall back to the default simple logging implementation (SimpleLog).
  • Load the class of the specified name from the thread context class loader (if any), or from the class loader that loaded the LogFactory class otherwise.
  • Instantiate an instance of the selected Log implementation class, passing the specified name as the single argument to its constructor.

See the SimpleLog JavaDocs for detailed configuration information for this default implementation.

Configuring the Underlying Logging System

The basic principle is that the user is totally responsible for the configuration of the underlying logging system. Commons-logging should not change the existing configuration.

Each individual Log implementation may support its own configuration properties. These will be documented in the class descriptions for the corresponding implementation class.

Finally, some Log implementations (such as the one for Log4J) require an external configuration file for the entire logging environment. This file should be prepared in a manner that is specific to the actual logging technology being used.

Using the Logging Package APIs

Use of the Logging Package APIs, from the perspective of an application component, consists of the following steps:

  1. Acquire a reference to an instance of org.apache.commons.logging.Log, by calling the factory method LogFactory.getInstance(String name). Your application can contain references to multiple loggers that are used for different purposes. A typical scenario for a server application is to have each major component of the server use its own Log instance.
  2. Cause messages to be logged (if the corresponding detail level is enabled) by calling appropriate methods (trace(), debug(), info(), warn(), error, and fatal()).

For convenience, LogFactory also offers a static method getLog() that combines the typical two-step pattern:

  Log log = LogFactory.getFactory().getInstance(Foo.class);

into a single method call:

  Log log = LogFactory.getLog(Foo.class);

For example, you might use the following technique to initialize and use a Log instance in an application component:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyComponent {

  protected Log log =
    LogFactory.getLog(MyComponent.class);

  // Called once at startup time
  public void start() {
    ...
    log.info("MyComponent started");
    ...
  }

  // Called once at shutdown time
  public void stop() {
    ...
    log.info("MyComponent stopped");
    ...
  }

  // Called repeatedly to process a particular argument value
  // which you want logged if debugging is enabled
  public void process(String value) {
    ...
    // Do the string concatenation only if logging is enabled
    if (log.isDebugEnabled())
      log.debug("MyComponent processing " + value);
    ...
  }

}
Java Source File NameTypeComment
AbstractLogTest.javaClass Generic tests that can be applied to any log adapter by subclassing this class and defining method getLogObject appropriately.
author:
   Sean C.
AltHashtable.javaClass
AltHashtableTestCase.javaClass Test the ability to force the LogFactory class to use some arbitrary Hashtable implementation to store its mapping from context-classloader -> LogFactory object.
BadHashtablePropertyTestCase.javaClass Tests behaviour when the property is misconfigured.
BasicOperationsTestCase.javaClass Tests the basic logging operations to ensure that they all function without exception failure.
DummyException.javaClass Dummy exception that unit tests create instances of when they want to test logging of an Exception object.
LoadTestCase.javaClass
Log.javaInterface

A simple logging interface abstracting logging APIs.

LogConfigurationException.javaClass

An exception that is thrown only if a suitable LogFactory or Log instance cannot be created by the corresponding factory methods.


author:
   Craig R.
LogFactory.javaClass

Factory for creating Log instances, with discovery and configuration features similar to that employed by standard Java APIs such as JAXP.

IMPLEMENTATION NOTE - This implementation is heavily based on the SAXParserFactory and DocumentBuilderFactory implementations (corresponding to the JAXP pluggability APIs) found in Apache Xerces.


author:
   Craig R.
LogSource.javaClass

Factory for creating Log instances.

LogTestCase.javaClass
NullClassLoaderTestCase.javaClass Test cases for situations where getClassLoader or getContextClassLoader return null.
PathableClassLoader.javaClass A ClassLoader which sees only specified classes, and which can be set to do parent-first or child-first path lookup.

Note that this classloader is not "industrial strength"; users looking for such a class may wish to look at the Tomcat sourcecode instead.

PathableTestSuite.javaClass Custom TestSuite class that can be used to control the context classloader in operation when a test runs.

For tests that need to control exactly what the classloader hierarchy is like when the test is run, something like the following is recommended:

 class SomeTestCase extends TestCase {
 public static Test suite() throws Exception {
 PathableClassLoader parent = new PathableClassLoader(null);
 parent.useSystemLoader("junit.");
 PathableClassLoader child = new PathableClassLoader(parent);
 child.addLogicalLib("testclasses");
 child.addLogicalLib("log4j12");
 child.addLogicalLib("commons-logging");
 Class testClass = child.loadClass(SomeTestCase.class.getName());
 ClassLoader contextClassLoader = child;
 PathableTestSuite suite = new PathableTestSuite(testClass, child);
 return suite;
 }
 // test methods go here
 }
 
Note that if the suite method throws an exception then this will be handled reasonable gracefully by junit; it will report that the suite method for a test case failed with exception yyy.

The use of PathableClassLoader is not required to use this class, but it is expected that using the two classes together is common practice.

This class will run each test methods within the specified TestCase using the specified context classloader and system classloader.

SimpleLogTestCase.javaClass
UserClass.javaClass
ww__w___.___j_av__a2s_.___c___om | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.