Spring Framework Logging with Log4J

Spring Framework Logging with Log4J

In this article, I am going to discuss Spring Framework Logging with Log4J with Examples. Please read our previous article, where we discussed Web MVC in Spring Framework.

What is Log4J?

Log4j (Log for Java) is a widely used logging framework for Java applications. It provides a flexible and configurable logging mechanism that allows developers to generate log statements from their code to capture information about application events, errors, warnings, and debug messages. Log4j is known for its simplicity, performance, and extensibility.

Key Features of Log4j:
  • Logging Levels: Log4j supports different logging levels, including DEBUG, INFO, WARN, ERROR, and FATAL. Developers can choose the appropriate level for their log statements based on the severity of the message.
  • Configurable Logging Output: Log4j allows developers to configure the destination of log statements. It supports various output options such as console output, file output, and network output. Developers can specify different log appenders to direct log statements to different outputs simultaneously.
  • Flexible Logging Configuration: Log4j provides flexible configuration options to customize logging behavior. It supports configuration through XML, properties files, or programmatically. Developers can define logging thresholds, output formats, log rolling policies, and more.
  • Logging Hierarchies: Log4j supports hierarchical loggers, allowing developers to define a hierarchy of loggers based on different components or modules of their application. This enables fine-grained control over logging behavior at different levels of the application.
  • Filtering and Pattern Layouts: Log4j supports filtering log statements based on specific criteria. Developers can define filters to control which log statements are captured and processed. Additionally, Log4j provides pattern layouts, allowing developers to specify the format of log messages with placeholders for various information like timestamps, log levels, and loggers.
  • Pluggable Architecture: Log4j follows a modular and pluggable architecture. It allows developers to extend its functionality by implementing custom appenders, filters, and layouts to meet specific logging requirements. There are also additional appenders and extensions available from the Log4j ecosystem.
  • Performance: Log4j is designed for high-performance logging with minimal impact on application performance. It uses asynchronous logging and provides configuration options to control the buffer size and thread pool for log event processing.

Log4j has been widely adopted and integrated into numerous Java applications and frameworks due to its rich features and ease of use. However, it’s worth noting that Log4j 1.x, the previous major version, has reached its end of life and is no longer actively maintained or recommended for new projects due to security vulnerabilities. Log4j 2.x, the current version, addresses these vulnerabilities and provides various improvements and enhancements over its predecessor.

In conclusion, Log4j is a powerful logging framework for Java applications, offering flexibility, performance, and configurability. By using Log4j, developers can capture and manage log statements effectively, gaining insights into their application’s behavior, troubleshooting issues, and improving overall application quality.

Implementing Log4J in Spring Framework

Before starting the project, ensure that the required JAR files are in the project’s “Referenced Libraries” folder.

Implementing Log4J in Spring Framework

Apart from these JAR files, another JAR file is required for JDBC. This JAR file is for the Log4J module. It can be found at https://repo1.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar. Paste the downloaded JAR file into the “Referenced Libraries” directory.

Step 1: Create a new file called HelloWorld.java in the src/ directory. Add the following contents to the file:

public class HelloWorld
{
    private String msg;
    
    public void setMsg(String msg)
    {this.msg = msg;}

    public void print()
    {System.out.println(msg);}
}

Step 2: In the src/there must be a file called App.java. This file contains the main function and was created when the project was created (by VS Code). Modify the file to have the following content:

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
    static Logger logger = Logger.getLogger(App.class.getName());
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        logger.info("Creating HelloWorld object...");
        HelloWorld hw = (HelloWorld) context.getBean("hw");
        logger.info("HelloWorld object created!");
        hw.print();
        logger.info("Exiting program now...");
    }
}

The main function creates a HelloWorld object from the Beans.xml file. Several log statements are printed using the logger.info() function.

Step 3: Create a new file called Beans.xml in the src/ directory. Add the following contents to the file:

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "hw" class = "HelloWorld">
      <property name = "msg" value = "Hello World!"/>
   </bean>
</beans>

This file is responsible for defining the data source (which is the MySQL server) and injecting it into the EmployeeJDBC object. This file is also similar to the file from the previous project. However, the only difference is that we have added two more sections to the file (which are in the red box highlighted above). This handles transaction management.

Step 4: Create a new file called log4j.properties in the src/ directory. This file will be used to initialize the log4j logger. Add the following contents to the file:

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=/Users/log.txt

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

Remember to provide the configuration file with a proper directory and file name (as shown in line 7).

Step 5: Compile and execute the application. Ensure compilation is successful. The terminal output is as follows:

Spring Framework Logging with Log4J

The log output will be printed to the file provided in line 7 of the properties file. The contents of the file are supposed to be as follows:

Spring Framework Logging with Log4J with Examples

As can be seen, all the required logger print operations execute. Congratulations! You have completed the log4j application in Spring Framework!

In the next article, I am going to discuss Spring Core Container. Here, in this article, I try to explain Spring Framework Logging with Log4J with Examples. I hope you enjoy this Spring Framework Logging with Log4J article.

Leave a Reply

Your email address will not be published. Required fields are marked *