Implement Logger in your java framework

Pallavi Gaikwad
Posted on 3rd Apr 2024 1:47 PM | 10 min Read | 60 min Implementation

#log4j #slf4j #logger-frameworks #java

In this Blog ,We introduce about Logging Framework and in that we can discuss and know about Log4j and Slf4j


Any software application or a system can have bugs and issues in testing or production environments. Therefore, logging is essential to help troubleshoot issues easily and introduce fixes on time. However, logging is useful only if it provides the required information from the log messages without adversely impacting the system’s performance.


Introduction:

logging is typically implemented using the built "-in java.util.logging" package or third-party logging frameworks like Log4j, Logback, or SLF4J. These frameworks provide classes and methods to create loggers, format log messages, specify log levels, and route log output to various destinations such as the console, files, databases, or remote servers.


What is Logging Framework?

To overcome all the problems while tracing our application then we use logging framework.


Advantage of Logging:

Quick Debugging.

Problem diagnosis.

Easy Maintenance.


Drawbacks of Logging:

Logging framework needs to write some extra code in our java Application, it will increase overhead to application.

Logging framework will provide some extra code in application, so it will increase application length.


Introduction of Log4j:

Log4j is a reliable , fast and flexible framework written in java

It is provided by Apache software foundation.


Log4j Features:

Allow more than one thread at a time without providing data inconsistency

Log4j will not slow down the application execution , it will be optimized to improve application performance.

Log4j is providing environment to send logging message to more than one output appender (DB|Console|File)

Log4j uses multiple levels like ALL,TRACE,DUBUG,INFO, WARN,ERROR and FETAL to generate message.


Log4j Component:


Here we know how component works....


Levels:

The main intension of level object is to define granularity and priority of any logging information.

Log4j API has provided the following levels of logging messages.

Note: this is giving priorities for the logging message in following order.

ALL>TRACE>DEBUG>INFO>WARN>ERROR>FATAL>OF


Log Manager:

Log Manager is the central component , it able to manage Log4j framework ,it will read all the initial configuration detail from the configure file.


Logger:

This object is responsible to get logging message from java application.

This object must be created inside class for which Log4j is required.

Ex. Controller ,Services, Repository..etc.(Needs Log4j server if we get any exception/error inside these classes we can trace those into log file.)

Do not create logger object if we do not want to logging for class

Ex. Model/Entity


Filter:

The main intension of filter object is used to analyze logging information and takes the decision weather the message must be logged or not


Object Render:

This object will be used by layout object in order to get string representation of the several objects which are passed through log4j framework.


Appender:

This object is send message to application.(where to store log message).Each and every Appender object must have at least one destination object in order to send logging message.

Type of Appender :

ConsoleAppender : Print Log message on console

FileAppender : store log message in .log file

JDBCApeender : store log message on database table

Ftp/TelnetAppender : send data from one server to another server

SMTPAppender : send log message to email


Layout:

The main intension of layout object is to format logging message in different styles. Layout object is used by appender object just before publishing logging message.

Type of Layout:

Simple Layout: Print Message as it is given by application

HTML Layout: Print message as HTML file

XML Layout: print message as xml Output

Pattern Layout: print message as given pattern by programmer.(EX. dd/mm/yyyy, or mm/dd/yyyy)


Destination:

Destination object is typically referred to as an "Appender" An Appender is responsible for outputting log events to a specific destination, such as a file, console, database, or a custom location.


Introduction of Slf4j:

SLF4J (Simple Logging Façade for Java) serves as a simple façade or abstraction for various logging frameworks, such as Logback, Log4j, JUL (java.util.logging), and others. It provides a unified API for logging in Java applications while allowing developers to switch between different logging implementations easily without changing the codebase significantly.


Why Use SLF4J:

>SLF4J is a logging façade that provides a simple abstraction over various logging frameworks like Logback, Log4j, etc.

>Using SLF4J allows you to write log statements without being tied to a specific logging implementation. You can switch between logging implementations easily without changing your code.

>It promotes good logging practices by providing consistent APIs and separating the logging interface from its implementation.

>SLF4J supports parameterized logging, which improves performance by avoiding unnecessary string concatenation when logging messages.


What is the use of Priorities method:


A. DEBUG : This method is used to print a final/ success message

Ex: Employee created with ID-EMP-1100 successfully


B. INFO: this method is used to print current status in execution

Ex. request come to controller method

object sent to service layer

service returned back to controller

try block execution completed


C. WARN: This method is used to print warning in application

Ex. File object is created but never closed

variable is created , but not used


D. ERROR: This method is used to print any general exception

Ex. NullPointerException , ArithmaticException. etc.

( Application Id is null can not be proceed.)


E. FATAL: This method is used to print any high level exception that makes Stopping application Usage.

Ex. Database connection is not working.

Network server/ Middleware Server is down.


F. OF: This method is used for if you don't want print any message then you use OF(NOT APPLICABLE)


Let's Implement Log4j & slf4j logging in your framework


1 - Dependency of Log4j & Slf4j

<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.1.0-alpha0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.19.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.1.0-alpha0</version>
<scope>runtime</scope>
</dependency>
</dependencies>


2 - Property file - (You can save it .properties)

#For Console Appender
log4j.rootLogger= DEBUG,CONSOLE,FILE,DB
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p -%m%n
#For File Appender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=log4j.log
log4j.appender.FILE.File.MaxFileSize=512KB
log4j.appender.FILE.File.MaxBackupIndex=3
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p -%m%n


Explanation of log4j.properties File


Root Logger Configuration:

log4j.rootLogger= INFO,CONSOLE,FILE

The root logger of Log4j. It specifies that log messages of level INFO and above should be logged to the appender named "CONSOLE".


Appender Configuration:

log4j.appender.abc=org.apache.log4j.ConsoleAppender

An appender named "CONSOLE" and specifies that it should use the ConsoleAppender class. An appender is responsible for outputting log messages to different destinations such as the console, file, or network.


Appender Target Configuration:

log4j.appender.abc.Target = System. Out

The target for the appender "CONSOLE".. Here, it's set to 'System. Out', meaning log messages will be output to the console.


Appender Layout Configuration:

log4j.appender.abc.layout= org.apache.log4j.PatternLayout

The layout used by the appender abc. Here, it's using HTML Layout, which formats log messages in HTML format.


Layout Conversion Pattern:

log4j.appender.abc.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %n %M %m

The conversion pattern for the layout used by appender abc. It defines the format in which log messages will be output.

Here's what each part means:

  1. %p: Log level (INFO, DEBUG, WARN, ERROR, etc.)
  2. %d: Date and time of the logging event
  3. %c: Class name of the logger
  4. %M: Method name where the logging call was made
  5. %m: The actual log message
  6. %n: Newline character
  7. %t: To output the name of the thread that generated the logging event.
  8. %L: To output the line number from where the logging request was issued.
  9. %I: To output location information of the caller which generated the logging event.



Implementation of Log4j and Slf4j:


Console Appender:-

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

import java.io.IOException;
public class TestApp
{
//step3 3.create logger object
private static final Logger Log = LoggerFactory.getLogger(TestApp.class);
public static void main(String[] args) throws IOException {
Log.debug("From debug");
Log.info("From info");
Log.warn("From Warn");
Log.error("From Error");
}
}


private static Logger Logger = LoggerFactory.getLogger(FileAppend.class);

Logger Object Creation: A logger object named 'Logger' is created, which is used to log messages throughout the application. It's static, so it belongs to the class itself rather than any specific instance of the class.

Layout lay = new PatternLayout("%p %d %c %M %m %n");

Layout Definition: Two layouts are defined and the other is "PatternLayout." These are used to format log messages.

Appender app = new ConsoleAppender(lay);

Appender Creation: A ConsoleAppender named app is created, which appends log events to the console. It is constructed with the layout defined earlier.

Logger-Appender Attachment: The appender created is attached to the logger using the addAppender() method.

Log.debug("From Debug");
Log.info("From info");
Log.warn("From Warn");
Log.error("From Error");
Log.fatal("From Fatal");

Logging Statements: Various log statements are made using different log levels (trace, debug, info, warn, error, and fatal) using the logger object. Each statement logs a message at a specific log level.


Console Appender Simple Layout Output:-


File Appender:-

package org.example.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class FileAppend
{
private static final Logger Log= LoggerFactory.getLogger(FileAppend.class);

public static void main(String[] args) throws IOException {

Log.debug("From debug");
Log.info("From info");
Log.warn("From Warn");
Log.error("From Error");
}
}


Note: When we create FileAppender it will create a file to given path.

In File Output



File Appender Using HTML Layout Output:-


GitRepository: https://github.com/PallaviGajananGaikwad/Logger.git


Conclusion:

Both Log4j and SLF4J play crucial roles in Java application development, helping developers effectively manage and analyze application logs for debugging, monitoring, and troubleshooting purposes.


All Comments ()
Do You want to add Comment in this Blog? Please Login ?