Introduction to Log4j

Varun Varshney
BYJU’S Exam Prep Engineering
6 min readOct 26, 2018

Log4j is a fast, flexible and reliable logging framework (APIS) written in Java developed in early 1996. It is distributed under the Apache Software License. Log4J has been ported to the C, C++, C#, Perl, Python, Ruby and Eiffel Languages. It is a tool used for small to large scale Selenium Automation projects.

log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.

Why use Log4j?

  • It is an open source
  • With Log4j, it is possible to store the flow details of our Selenium Automation in a file or databases
  • Log4j is used for large as well as small projects
  • In Log4j, we use log statements rather than SOPL statements in the code to know the status of a project while it is executing.

Log4j Features

  • It is thread-safe.
  • It is optimized for speed.
  • It is based on a named logger hierarchy.
  • It supports multiple output appenders per logger.
  • It supports internationalization.
  • It is not restricted to a predefined set of facilities.
  • Logging behavior can be set at runtime using a configuration file.
  • It is designed to handle Java Exceptions from the start.

Log4j has three main components:

  • loggers: Responsible for capturing logging information.
  • appenders: Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible for formatting logging information in different styles.

Loggers

It is responsible for logging information. To implement loggers into a project following steps need to be performed.

Create an instance for logger class: Logger class is a Java-based utility that has got all the generic methods already implemented to use log4j.

The Logger class provides different methods to handle logging activities. It provides two static methods for obtaining a Logger Object.

  • Public static Logger getRootLogger()
  • Public static Logger getLogger(String name)

Define the Log4j level:

Primarily there are five kinds of log levels

  • All — This level of logging will log everything ( it turns all the logs on )
  • DEBUG — print the debugging information and is helpful in development stage
  • INFO — print informational message that highlights the progress of the application
  • WARN — print information regarding faulty and unexpected system behavior.
  • ERROR — print error message that might allow system to continue
  • FATAL — print system critical information which are causing the application to crash
  • OFF — No logging

Appenders:

It is used to deliver LogEvents to their destination. It decides what will happen with log information. In simple words, it is used to write the logs in file. Following are few types of Appenders

  • ConsoleAppender logs to standard output
  • File appender prints logs to some file
  • Rolling file appender to a file with maximum size

Layouts:

It is responsible for formatting logging information in different styles.

The Layout Types

The top-level class in the hierarchy is the abstract class org.apache.log4j.Layout. This is the base class for all other Layout classes in the log4j API.

The Layout class is defined as abstract within an application, we never use this class directly; instead, we work with its subclasses which are as follows:

  • DateLayout
  • HTMLLayout
  • PatternLayout
  • SimpleLayout
  • XMLLayout

How log4j is configured?

To configure log4j we have to decide which appender to implement. Accordingly, parameters of appender will be set.

  • We will use ALL level and RollingFileAppender
  • We will do two configurations or logs,

First: root logger, that will write all system generated logs in file name i.e. Root.logs

Second: Will write the information generated by manual commands in code into the file name- App.logs

  • Layout will be PatternLayout

Step 1: Create Dependencies in pom.xml file of log4j

Step 2: Create log4j.properties File

Step 3: Store log4j.properties File

Put the log4j.properties file in the path as follows:

/src/main/resources/log4j.properties

Step 4: Create Two Log Files

Path of the files, as follows:

/projects/Demo/Root.logs

/projects/Demo/App.logs

Step 5: Create Sample Program:

import org.apache.log4j.*;

import org.testng.annotations.Test;

public class Demo

{

static Logger log=Logger.getLogger(“Demo”);

@Test

public void main2()

{

log.trace(“Trace Message!”);

log.debug(“Debug Message!”);

log.info(“Info Message!”);

log.warn(“Warn Message!”);

log.error(“Error Message!”);

log.fatal(“Fatal Message!”);

}

}

Step 6: Now Run the Class and observe the log Files:

App.logs

Root.Logs

Important Points:

1)We can use Logger method in multiple classes but for that we have to edit . the configurations for each class in log4j.properties file.

For Example:

In the above Example:

We make:

a) Root Logs: which had all the logs of the classes.

b) Application Logs: which had 3 logs file as App1.logs , App2.logs , and App3.logs for each different classes.

2.) How do Levels Works?

A log request of level p in a logger with level q is enabled if p >= q. This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

The Following example shows how we can filter all our DEBUG and INFO messages. This program uses of logger method setLevel(Level.X) to set a desired logging level:

This example would print all the messages except Debug and Info:

import org.apache.log4j.*;

public class LogClass {
private static org.apache.log4j.Logger log = Logger.getLogger(LogClass.class);

public static void main(String[] args) {
log.setLevel(Level.WARN);

log.trace("Trace Message!");
log.debug("Debug Message!");
log.info("Info Message!");
log.warn("Warn Message!");
log.error("Error Message!");
log.fatal("Fatal Message!");
}
}

When you compile and run the LogClass program, it would generate the following result −

Warn Message!
Error Message!
Fatal Message!

3.)

log4j.appender.FILE.Append=true :

This properties of File Appender will append the logs each time a class is executed.

log4j.appender.FILE.Append=false:

This properties of File Appender will not append the logs each time a class is executed i.e each time store current logs.

4.) HTMLLayout Example

Following is a simple configuration file for HTMLLayout:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/htmlLayout.html
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Example
log4j.appender.FILE.layout.LocationInfo=true

Now consider the following Java Example which would generate logging information:

import org.apache.log4j.Logger;import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(log4jExample.class.getName());

public static void main(String[] args)throws IOException,SQLException{
log.debug("Hello this is an debug message");
log.info("Hello this is an info message");
}
}

Compile and run the above program. It would create an htmlLayout.html file in /usr/home/log4j directory which would have the following log information:

Log session start time Mon Mar 22 13:30:24 AST 2010

You would use a web browser to open htmlLayout.html file. It is also important to note that the footer for the </html> and </body> tags is completely missing.

One of the big advantages of having log file in HTML format is that it can be published as a web page for remote viewing.

5.) What are Pros and Cons of Logging?

Following are the Pros and Cons of Logging −

Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.

Logging does have its drawbacks also. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible.

Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.

--

--