Java Commons Logging Tutorial

1- Commons Logging do?

In your Java application, you want to write code to log messages during its working? You can use one of three library Logger follows:
  • Log4J Logger
  • Jdk14 Logger
  • Simple Logger
Commons Logging is a library that allows you to work with one of three libraries above easier. So to write a program log, Stand alone 'Commons Logging' can not be a Logger. A similar way, you work with java.io to process stream,  Commons IO is a library written based on java.io help you more easily handled IO, Common IO irreplaceable java.io.
So you have 3 choices:
What you choose does not matter, Logger are treated the same way with the support of the Commons Logging.

2- The goal of documentation

In this guide I will show you how to work with:
  • Commons Logging + Log4J Logger

3- Commons Logging + Log4J Logger

3.1- Library

Commons Logging Library:
Maven:
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.3</version>
</dependency>
Log4J Logger Library:
Maven:
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

3.2- Create project

  • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.o7planning</groupId>
    <artifactId>CommonsLoggingTutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    
</project>

3.3- A simple example HelloWorld (Log to Console)

In this step we will make a simple HelloWorld example, it will write Log to the console.
  • HelloWorld.java
package org.o7planning.tutorial.commonslogging;

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

public class HelloWorld {

    private static final Log log = LogFactory.getLog(HelloWorld.class);

    public static void main(String[] args) {
        log.debug("Example debug message ..");
        log.info("Example info message ..");
        log.warn("Example warn message ..");
        log.error("Example error message ..");
        log.fatal("Example fatal message ..");   
    }
}
  • commons-logging.properties
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

log4j.configuration=log4j.properties
  • log4j.properties
log4j.rootLogger=DEBUG, CA, NTEventLog

#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
In fact you can configure Commons Logging to use other Logger libraries, not log4j:
Run class HelloWorld:
With Log4j you can configure in the xml file, and the xml configuration is easy and straightforward than properties file.
Open file commons-logging.properties and change:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

log4j.configuration=log4j.xml
  • log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
        </layout>
    </appender>



    <root>
        <priority value="debug" />
        <appender-ref ref="MyConsole" />
    </root>

</log4j:configuration>
Running class HelloWorld and view Log in Console.

3.4- For example, more complex (Log out file)

Next we will continue with a more complex example, the Log to file.
  • AdminApplication.java
package org.o7planning.tutorial.commonslogging.admin;

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

public class AdminApplication {

    private static final Log log = LogFactory.getLog(AdminApplication.class);

    public static void main(String[] args) {
        log.debug("Example debug message ..");
        log.info("Example info message ..");
        log.warn("Example warn message ..");
        log.error("Example error message ..");
        log.fatal("Example fatal message ..");

        try {
            raiseException();
        } catch (Exception e) {
            log.fatal("<Some Object>", e);
        }
    }

    private static void raiseException() throws Exception {
        throw new Exception("Test Exception");
    }
}
 
  • FrontEndApplication.java
package org.o7planning.tutorial.commonslogging.frontend;

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

public class FrontEndApplication {

    private static final Log log = LogFactory.getLog(FrontEndApplication.class);

    public static void main(String[] args) {
        log.debug("Example debug message ..");
        log.info("Example info message ..");
        log.warn("Example warn message ..");
        log.error("Example error message ..");
        log.fatal("Example fatal message ..");
    }
}

 
Cấu hình thêm vào trong log4j.xml, thêm vào đoạn cấu hình:
  <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
      <param name="File" value="logs/admin.log" />
      <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern"
              value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
      </layout>
  </appender>

  <appender name="FrontEndFileAppender" class="org.apache.log4j.FileAppender">
      <param name="File" value="logs/frontEnd.log" />
      <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern"
              value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
      </layout>
  </appender>

  <!-- logger name must by package name! -->
  <logger name="org.o7planning.tutorial.commonslogging.admin">
      <level value="ERROR" />
      <appender-ref ref="AdminFileAppender" />
  </logger>

  <!-- logger name must by package name! -->
  <logger name="org.o7planning.tutorial.commonslogging.frontend">
      <level value="DEBUG" />
      <appender-ref ref="FrontEndFileAppender" />
  </logger>
  • log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
      <param name="Target" value="System.out" />
      <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
      </layout>
  </appender>




  <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
      <param name="File" value="logs/admin.log" />
      <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern"
              value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
      </layout>
  </appender>

  <appender name="FrontEndFileAppender" class="org.apache.log4j.FileAppender">
      <param name="File" value="logs/frontEnd.log" />
      <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern"
              value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
      </layout>
  </appender>

  <!-- logger name must by package name! -->
  <logger name="org.o7planning.tutorial.commonslogging.admin">
      <level value="ERROR" />
      <appender-ref ref="AdminFileAppender" />
  </logger>

  <!-- logger name must by package name! -->
  <logger name="org.o7planning.tutorial.commonslogging.frontend">
      <level value="DEBUG" />
      <appender-ref ref="FrontEndFileAppender" />
  </logger>


  <root>
      <priority value="debug" />
      <appender-ref ref="MyConsole" />
  </root>

</log4j:configuration>
There is a note on the order of tags when you configure log4j.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- render -->
    <renderer></renderer>
    <renderer></renderer>
    <renderer></renderer>
    
    <!-- appender -->
    <appender></appender>
    <appender></appender>
    <appender></appender>
    
    
    <!-- plugin -->
    <plugin></plugin>
    <plugin></plugin>
    <plugin></plugin>
    
    <!-- logger -->
    <logger></logger>
    <logger></logger>
    <logger></logger>
    
    <!-- category -->
    <category></category>
    <category></category>
    <category></category>
    
    <!-- root -->
    <root></root>
    <root></root>
    <root></root>
    
    <!-- loggerfactory -->
    <loggerfactory></loggerfactory>
    <loggerfactory></loggerfactory>
    <loggerfactory></loggerfactory>
    
    <!-- categoryfactory -->
    <categoryfactory></categoryfactory>
    <categoryfactory></categoryfactory>
    <categoryfactory></categoryfactory>

</log4j:configuration>
Run class AdminApplication:
Run class FrontEndApplication
A folder 'logs' has been created and has two log files (admin.log & frontEnd.log)