Java

Java Logging Frameworks

java logging framework

Logging is not the Core requirement of any Business, but we can’t ignore it because it is very important part of any application which helps to developer to debug the code or analyze the issues.

In some cases developers using Synchronous logging, which impacts the performance. Logging library like Log4j, Logback, Log4j2 provides Asynchronous Logging. which is good for performance point of view.

In Java we have multiple Logging libraries like Log4j, Logback, Log4j2, etc. Here we will see one by one and what are differences between them.

Writing Log Messages with SLF4J

SLF4J is not a logging library. It is an abstraction layer which helps up to use any logging library (Java.util.logger, Log4j, Logback, Log4j2).

SLF4J provides us such type of feature where we can change our logging framework anytime without changing a single line of code. We only need to change the dependencies of different framework which implements SLF4J Interface.

Writing log messages with SLF4J is very easy. Here first we need to call getLogger static method with help of LoggerFactory Class. Then we can call any of the debug, info, warning or error method to write the log message. Here we can see below example :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClass {

Logger logger = LoggerFactory.getLogger(MyClass.class);

public void myMethod() {
//.....
logger.info("This is an info message");
logger.warn("This is warning message");
logger.debug("This is debug message");
logger.error("This is error message");
}

}

Apache Log4j

Required dependencies

For Maven user can add below dependencies in pom.xml.

<dependency> 
    <groupId>log4j</groupId> 
    <artifactId>log4j</artifactId> 
    <version>1.2.17</version> 
</dependency>

For non-maven user can download jar from log4j official page, and put in the project library path manually. 

As we discussed above we can use SLF4J for log4If logging, for this we need to add below dependency in pom.xml.

<dependency> 
    <groupId>org.slf4j</groupId> 
    <artifactId>slf4j-log4j12</artifactId> 
    <scope>test</scope> 
</dependency>

 

Configuring Log4j

 
 
 

Logback

Required dependencies

Configuring Log4j

Apache Log4j2

Required dependencies

Configuring Log4j

Leave a Reply

avatar
  Subscribe  
Notify of