Log4j

Log4j Enable/Disable Logging Example

Let’s say developers want to disable or enable the Log4j framework by simply clicking some checkboxes. The advantage of this is that when developers use the Log4j framework in the production environment and want to enable logging at any time, they just don’t need to change the XML or the properties file from the local machine and then upload it. In this tutorial, I will show you how to enable or disable the Log4j mechanism through a simple web application.

1. Introduction

Printing messages to the console is an integral part of the development testing and the debugging of a Java program. If developers are working on a Server side application, where they cannot see what’s going on inside the server, then their only visibility tool is a log file.

Without logs, developers cannot do any debugging or see what’s going on inside the application. Java has pretty handy System.out.println() methods to print something on the console, which can also be routed to a log file but it is not sufficient for a real-world Java application.

If developers are running a Java program in Linux or in the Unix based systems, Log4j or SLF4j or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System.out.println() statements.

1.1 What is Log4j?

Log4j is a simple, flexible, and fast Java-based logging framework. It is thread-safe and supports internationalization. We mainly have 3 components to work with Log4j:

  • Logger: It is used to log the messages
  • Appender: It is used to publish the logging information to the destination like file, database, console etc
  • Layout: It is used to format logging information in different styles

1.1.1 Log4j Logger Class

Logger class provides the methods for the logging process. We can use the getLogger() method to get the Logger object. The syntax is given below:

static Logger log = Logger.getLogger(YourClassName.class);

Logger class has 5 logging methods which are used to print the status of an application:

DescriptionMethod Syntax
debug(Object message)It is used to print the message with the level org.apache.log4j.Level.DEBUG.public void debug(Object message)
error(Object message)It is used to print the message with the level org.apache.log4j.Level.ERROR.public void error(Object message)
info(Object message)It is used to print the message with the level org.apache.log4j.Level.INFO.public void info(Object message)
fatal(Object message)It is used to print the message with the level org.apache.log4j.Level.FATAL.public void fatal(Object message)
warn(Object message)It is used to print the message with the level org.apache.log4j.Level.WARN.public void warn(Object message)
trace(Object message)It is used to print the message with the level org.apache.log4j.Level.TRACE.public void trace(Object message)

To summarize, the priority level is given below.

Trace < Debug < Info < Warn < Error < Fatal

Where org.apache.log4j.Level.FATAL has the highest priority and org.apache.log4j.Level.Trace the lowest.

1.1.2 Log4j Appender Interface

Appender is an interface which is primarily responsible for printing the logging messages to the different destinations such as console, files, sockets, database etc. In Log4j we have different types of Appender implementation classes:

Fig. 1: Log4j Appenders
Fig. 1: Log4j Appenders

1.1.3 Log4j Layout Class

Layout component specifies the format in which the log statements are written into the destination repository by the Appender. In Log4j we have different types of Layout implementation classes:

Fig. 2: Log4j Layout
Fig. 2: Log4j Layout

1.2 Why prefer Log4j over System.out.println?

Below are some of the reasons, which are enough to understand the limitation of using System.out.println():

  • Any logging framework including allows developers to log debugging information to a log level which can be used as filtering criteria, i.e. one can disable the message belongs to a particular log level. For e.g., Developers would be more concerned to see the WARN messages than DEBUG messages in the production environment
  • Logging framework can produce better outputs and metadata which helps to troubleshoot and debug. For e.g., Log4j allows to print formatted output by specifying a formatting pattern i.e. by using PatternLayout one can include a timestamp, class name etc

Now, open up the Eclipse Ide and let’s start building the application!

2. Log4j Enable/Disable Logging Example

Below are the steps involved in developing this application.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Log4j Jar. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Application Project Structure
Fig. 3: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project
Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location‘ will be selected. Just click on next button to proceed.

Fig. 5: Project Details
Fig. 5: Project Details

Select the ‘Maven Web App‘ Archetype from the list of options and click next.

Fig. 6: Archetype Selection
Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters
Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

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>Log4jEnableDisableEx</groupId>
	<artifactId>Log4jEnableDisableEx</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Log4j, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

In this example, we are using the most stable Log4j version (i.e. log4j-1.2.17) in order to set-up the logging framework. The updated file will have the following code:

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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Log4jEnableDisableEx</groupId>
	<artifactId>Log4jEnableDisableEx</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Log4jEnableDisableEx Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>Log4jEnableDisableEx</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.log4j.enable.disable.

Fig. 9: Java Package Name (com.jcg.log4j.enable.disable)
Fig. 9: Java Package Name (com.jcg.log4j.enable.disable)

Once the package is created, we will need to create the implementation class. Right-click on the newly created package, New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation

A new pop window will open and enter the file name as: LogServlet. The implementation class will be created inside the package: com.jcg.log4j.enable.disable.

Fig. 11: Java Class (LogServlet.java)
Fig. 11: Java Class (LogServlet.java)

3.2.1 Implementation of WebServlet Controller Class

Let’s write a quick Java program in order to quickly enable or disable the Log4j configuration. Add the following code to it:

LogServlet.java

package com.jcg.log4j.enable.disable;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

@WebServlet("/loggingServlet")
public class LogServlet extends HttpServlet {

	static Logger logger = Logger.getLogger(LogServlet.class);

	private static final long serialVersionUID = 1L;

	/***** @see HttpServlet#HttpServlet() *****/
	public LogServlet() {
		super();
	}

	/***** @see doPost(HttpServletRequest req, HttpServletResponse resp) *****/
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		handleRequest(req, resp);
	}

	/***** @see handleRequest(HttpServletRequest req, HttpServletResponse resp) *****/
	public void  handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug("!.... Application Process Is Started ....!");

		resp.setContentType("text/html");
		PrintWriter writer = resp.getWriter();
		String value[] = req.getParameterValues("log4jMode");

		if(value != null) {
			for(String mode : value) {
				logger.debug("Reading Log4j Enable Or Disable Decision?= " + mode);

				/**** Setting Log4j Priority Mode As 'DEBUG' ****/
				if(mode.equalsIgnoreCase("DEBUG")) {
					logger.setLevel(Level.DEBUG);
					logger.debug("Enabled 'DEBUG' Mode ....!");
				}

				/**** Setting Log4j Priority Mode As 'INFO' ****/
				else if(mode.equalsIgnoreCase("INFO")) {
					logger.setLevel(Level.INFO);
					logger.info("Enabled 'INFO' Mode ....!");
				}

				/**** Setting Log4j Priority Mode As 'WARN' ****/
				else if(mode.equalsIgnoreCase("WARN")) {
					logger.setLevel(Level.WARN);
					logger.warn("Enabled 'WARN' Mode ....!");
				}

				/**** Setting Log4j Priority Mode As 'ERROR' ****/
				else if(mode.equalsIgnoreCase("ERROR")) {
					logger.setLevel(Level.ERROR);
					logger.error("Enabled 'ERROR' Mode ....!");
				}

				/**** Setting Log4j Priority Mode As 'OFF' ****/
				else {
					logger.setLevel(Level.OFF);					
				}
				logger.debug("!.... Application Process Is Completed ....!");
				writer.println("<h1>Selected Log4j Mode Is " + mode + ".</h1>");
			}
		}
		writer.close();
	}
}

3.3 Log4j Configuration File

Log4j will be usually configured using a properties file or XML file. So once the log statements are in place developers can easily control them using the external configuration file without modifying the source code. The log4j.xml file is a Log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.xml in the CLASSPATH.

To configure the logging framework, we need to implement a configuration file i.e. log4j.xml and put it into the src/main/resources folder. Add the following code to it:

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM 
          "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="OFF" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

3.4 Creating JSP View

Let’s write a simple JSP view containing the different Log4j priority mode checkboxes and a button to submit the HTML form. Add the following code it:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Log4j</title>
	    <script src="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jquery/3.2.1/jquery.min.js"></script>
	    <script type="text/javascript">
	        $(document).ready(function() {	            
	        	// Selecting One Checkbox At A Time
	            $(':checkbox').on('change', function() {
	                var th = $(this),
	                    name = th.prop('name');
	                if (th.is(':checked')) {
	                    $(':checkbox[name="' + name + '"]').not($(this)).prop('checked', false);
	                }
	            });
	        	
	            $('#loggingEnableDisable').on('submit', function(event) {
	            	var isChecked = false;
	            	var checkbox = document.getElementsByName("log4jMode");
	                for (var i = 0; i < checkbox.length; i++) {
	                    if (checkbox[i].checked) {
	                        isChecked = true;
	                        break;
	                    }
	                }
	                if (isChecked) {              
	                    $('#loggingEnableDisable').submit();
	                } else {
	                	document.getElementById('error').innerHTML="Please select a checkbox .....!";
	                	event.preventDefault();
	                }
	            });
	        });
	    </script>
	</head>
	<body>
	    <h1>Enable Or Disable Log4j</h1>
	    <form id="loggingEnableDisable" action="loggingServlet" method="post" enctype="application/x-www-form-urlencoded">
	        <!--Debug Mode -->
	        <input type="checkbox" id="ex_check1" name="log4jMode" value="DEBUG" /><span id="debugId">'Debug' Mode</span>
	
	        <!-- Info Mode -->
	        <input type="checkbox" id="ex_check2" name="log4jMode" value="INFO" /><span id="infoId">'Info' Mode</span>
	
	        <!-- Warn Mode -->
	        <input type="checkbox" id="ex_check3" name="log4jMode" value="WARN" /><span id="warnId">'Warn' Mode</span>
	
	        <!-- Error Mode -->
	        <input type="checkbox" id="ex_check4" name="log4jMode" value="ERROR" /><span id="errorId">'Error' Mode</span>
	
	        <!-- Off -->
	        <input type="checkbox" id="ex_check5" name="log4jMode" value="OFF" /><span id="errorId">Off</span>
	
	        <input type="submit" id="submitBtn" value="Send" />
	    </form>
	    <div id="error" style="color: red; padding: 12px 0px 0px 23px;"></div>
	</body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 12: How to Deploy Application on Tomcat
Fig. 12: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed where developers can quickly select the Log4j level as per the business requirement.

http://localhost:8085/Log4jEnableDisableEx/

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 13: Log4j Enable/Disable Webpage
Fig. 13: Log4j Enable/Disable Webpage

Mode Selected: DEBUG

DEBUG   2017-11-18 17:18:07,143 [http-bio-8085-exec-5] com.jcg.log4j.enable.disable.LogServlet  - Enabled 'DEBUG' Mode ....!
DEBUG   2017-11-18 17:18:07,145 [http-bio-8085-exec-5] com.jcg.log4j.enable.disable.LogServlet  - !.... Application Process Is Completed ....!

Mode Selected: INFO

DEBUG   2017-11-18 17:18:26,301 [http-bio-8085-exec-8] com.jcg.log4j.enable.disable.LogServlet  - !.... Application Process Is Started ....!
DEBUG   2017-11-18 17:18:26,303 [http-bio-8085-exec-8] com.jcg.log4j.enable.disable.LogServlet  - Reading Log4j Enable Or Disable Decision?= INFO
INFO    2017-11-18 17:18:26,303 [http-bio-8085-exec-8] com.jcg.log4j.enable.disable.LogServlet  - Enabled 'INFO' Mode ....!

Mode Selected: WARN

WARN    2017-11-18 17:18:43,407 [http-bio-8085-exec-10] com.jcg.log4j.enable.disable.LogServlet  - Enabled 'WARN' Mode ....!

Mode Selected: ERROR

ERROR   2017-11-18 17:18:56,885 [http-bio-8085-exec-4] com.jcg.log4j.enable.disable.LogServlet  - Enabled 'ERROR' Mode ....!

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for getting the developers started with the Log4j example. We will look into more features in the next posts. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Log4j Example.

Download
You can download the full source code of this example here: Log4jEnableDisableEx

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button