Close

Apache Commons Logging + log4j 2 Example

[Updated: Jul 4, 2017, Created: Jul 4, 2017]

This example shows how to use log4j 2 with JCL API.

Dependencies

As JCL does not have a ready to use adapter for log4j 2, we need to add the bridge dependency log4j-jcl, along with log4j 2 dependency.

pom.xml

<dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-core</artifactId>
   <version>2.8.2</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-jcl</artifactId>
   <version>2.8.2</version>
</dependency>

Log4j2 configuration

src/main/resources/log4j2.properties

appenders=xyz

appender.xyz.type = Console
appender.xyz.name = myOutput
appender.xyz.layout.type = PatternLayout
appender.xyz.layout.pattern = %d{yy-MM-dd HH:mm:ss:SSS} %-5p %c{1} [%L] - %m%n

rootLogger.level = info

rootLogger.appenderRefs = abc

rootLogger.appenderRef.abc.ref = myOutput

Using JCL API

package com.logicbig.example;

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

public class Example1 {
  
  private static Log log = LogFactory.getLog(Example1.class);

  public static void main(String[] args) throws IllegalAccessException, InstantiationException {
    
      log.info("in the main method");
  }
}

Output

17-07-04 13:08:54:079 INFO  Example1 [19] - in the main method

Example Project

Dependencies and Technologies Used:

  • commons-logging 1.2: Apache Commons Logging is a thin adapter allowing configurable bridging to other, well known logging systems.
  • log4j-core 2.8.2: The Apache Log4j Implementation.
  • log4j-jcl 2.8.2: The Apache Log4j Commons Logging Adapter.
  • JDK 1.8
  • Maven 3.3.9

JCL + Log4j2 Example Project Select All Download
  • jcl-with-log4j2
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources

See Also