Java Logging Techniques Summary(Commons-Logging Example)

1. In last chapter, we introduced Log4j in detail.

    How can we use commons-logging for the existing project?

    1) Add dependency for commons-logging in pom.

<dependency>
	<groupId>commons-logging</groupId>
	<artifactId>commons-logging</artifactId>
	<version>1.1.2</version>
</dependency>

    2) Test case

package edu.xmu.log4j;

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

public class CommonsLoggingExampleTest
{
	private static Log logger = LogFactory.getLog("edu.xmu");

	@Test
	public void test()
	{
		// TRACE < DEBUG < INFO < WARN < ERROR
		logger.trace("[TRACE] This is TRACE messate");
		logger.debug("[DEBUG] This is DEBUG message");
		logger.info("[INFO] This is INFO message");
		logger.warn("[WARN] This is WARN message");
		logger.error("[ERROR] This is ERROR message");
	}

}

   3) The configuration file is still log4j.properties in class path.

   4) Now we start test. And the result same with the result using Log4j.

   Summary:

        1) The integration of Log4j and Commons-logging is quite simple. We just change the way we get Logger.

        2) But in Log4j/JUL, we can change the Appender/Layout and their level in the Logger in code. And this is disabled by JCL.

        3) You may wonder how it comes using Log4j instead of JUL or other Logging System.

            Please refer to part 3 which illustrates the work flow of getLog in detail.

 

2. Introduction to Commons-Logging

        1) It's really simple using commons-logging which we should merely use two important class:

            1) org.apache.commons.logging.Log

            2) org.apache.commons.logging.LogFactory

        2) The level for each logger and appender/handler is defined in thier configuration files.

            Add appender/handler and layout/formatter is depreciated and cannot migrate to JCL.

 

3. What happened when we call LogFactory.getLog()?

Java Logging Techniques Summary(Commons-Logging Example)
 

 4. So we can add commons-logging.properties under class path to make it clear which Log System we are actually using.

# Set Log4j as logging implementation
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl
# Set JUL as logging implementation
# org.apache.commons.logging.Log=org.apache.commons.logging.impl.Jdk14Logger
# Set LogKit as logging implementation
# org.apache.commons.logging.Log=org.apache.commons.logging.impl.LogKitLogger
# Set SimpleLog as logging implementation
# org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog

Reference Links:

    1) http://commons.apache.org/proper/commons-logging/guide.html

    2) http://blog.163.com/[email protected]/blog/static/444125552008102135348299/

    3) http://articles.qos.ch/thinkAgain.html