Java Commons Logging Tutorial with Examples
1. What is Commons Logging?
No ADS
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
No ADS
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>
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>
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:
commons-logging.properties
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.
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)
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials