Log4J

Log4j is framework which helps the java user to record the messages (logs) during the execution time. Logs are nothing but the detailed execution steps

Log4j write all the messages into files, files could be in many formats like text file, logfile, html file. Users have to configure the log4j before using it.


We can configure the log4j in two ways :

  • Properties file configuration
  • Xml file configuration


Components of log4j :

  • Logger
  • Appender
  • Layout
Sample code for Logging in log4j

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class FirstLog {
	static Logger log = Logger.getLogger(FirstLog.class);
	public static void main(String[] args) {
		//PropertiesConfigurator is used to configure logger from properties file
        PropertyConfigurator.configure("C:\\~\\log4j.properties");
 
        //log the message to file
        log.trace("This is a debug message");
        log.info("This is an info message");
	}
}

1. Logger

Logger captures the log messages generated by the framework, and it passes the logs to appends. Logger decides where to send the information like whether to file or to console. Loggers also decide what priority level to be captured.

Logger Priority Levels : All the levels are static variable and every level indicates a specific int value, as int value increses the rank also increases i.e max int values has max rank, least int value has least rank.

ALL -Integer.MIN_VAL : The ALL has the lowest possible rank and lowest int values, it is intended to turn on all logging.

TRACE - 5000 : This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy after ALL.

DEBUG - 10000 : To debug application, develper give the priority to debug. Level of message logged will be focused on providing support to a application developer

INFO - 20000 : Provides informational messages that highlight the progress of the application execution.

WARN - 30000 : The messages coming out of this level may not halt the progress of the system, but informs the user something unexpected is happening

ERROR - 40000 : The ERROR level designates error events that might still allow the application to continue running, means a particular part is failing but not a showstopper.

FATAL - 50000 : The FATAL level designates very severe error events that will presumably lead the application to abort, means it is a showstopper.

OFF - Integer.MAX_VAL : Does not capture any log and it's int value is Maximum value an integer can hold.

2. Appender

Appenders writes the log messages decided by the logger into file or to database. Appenders delegates the message to the formatter. There diffreent kind of appenders

  • FileAppender : It appends the message to a file.
  • RollingFileAppender : It also appends the messages to the file with filesize limit, when the file reachs the size limit automatically it creates another file and adds the messages.
  • DailyRollingFileAppender : It is Similar to Rolling File Appender, but it creates the files based on the given frequency.
  • ConsoleAppender : This appends to the console of the system.
  • SMTPAppender : This sends mail to the specific mail when an priority level occurs, example : sends mail when FATAL error occurs.
  • SysyLogAppender : Appends to a remote syslog domain.

3. Layout

The Layout component defines the format in which the log statements are written to the log destination by appender, like html or .log so on. There are diffrent kind of layout are present

  • SimpleLayout : it presents the log level - log messages format
  • PatternLayout : formats the output based on a conversion pattern specified, or if no conversuon specified, it takes the default conversion pattern
  • HTMLLayout : present the log messages as HTML table to the user.
  • XMLLayout : It provides the logs in the format of XMl.

Install / Associate Log4J

We can associate log4j with our framework in few steps.

1. Goto apache log4j site : https://logging.apache.org/log4j/1.2/
2. Click download Link
log4j-homepage-java-selenium

3. Click log4j.version.zip file from the table for windows
download-log4j-java-selenium

4. Click on the recommended mirror site link ( it may change based on your location )
mirror-site-log4j-java-selenium

5. Extact the downloaded zip file, and you can find the log4j.version.jar file
contents-of-zip-log4j-java

6. Open Eclipse and goto build path of the project
7. Add the log4j jar using Add External jar option
java-build-path-log4j

8. Inside java class try to type Logger, you should get suggestion from the Log4j. If you are seeing below suggesion your installation is succesfull.
import-logger-log4j-java-selenium

Log4J with Properties file

We can configure the log4j using properties file, properties file is nothing but hold the key value pair.

Properties File:
properties-file-log4j-java-selenium

Explanation of Properties File : 1. Logger section defines what is the level of Priority and where it send the logs. Here the Priority is 'DEBUG' and destination is 'file'


							# Root logger denotes where to write and priority level to write
log4j.rootLogger=DEBUG, file
							


2. Appender Section defines the details of the destination, which nothing but what is the type of appends, file location and the file size. Here Appender Type is RollingFileAppender, File Location is C:~\\firstLogOutput.log, file Size :10mb.


							# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\~\\firstLogOutput.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
							


3. Layout defines how the out put should look like. Here layout type is PatternLayout. Refer for Pattern Layout


								# layout of the log output pattern
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
								


Integration of Properties file with Log4J
After defining the values in properties file we have to integrate the properties file to the log4j system. Please find the steps to integrate

1. Create java class inside java Project.

2. Create the logger object by calling the getLogger method from the Logger Class, pass the Log name as parameter, most of the tie people pass the class name as parameter.


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


3. Load the peroperties file using configure methid from PropertyConfigurator class, pass the properties file path as the parameter.


							//PropertiesConfigurator is used to configure logger from properties file
							PropertyConfigurator.configure("C:\\~\\log4j.properties");
							


4. Call the methosd from the Logger class object (log)


								//log the message to file
								log.trace("This is a debug message");
								log.info("This is an info message");
								


5. Execute the file like normal java class and find the output file.

Complete program for Log4j with prperties file


							import org.apache.log4j.Logger;
							import org.apache.log4j.PropertyConfigurator;
							
							public class FirstLog {
								static Logger log = Logger.getLogger(FirstLog.class);
								public static void main(String[] args) {
									//PropertiesConfigurator is used to configure logger from properties file
											PropertyConfigurator.configure("C:\\~\\log4j.properties");
							 
											//log the message to file
											log.trace("This is a debug message");
											log.info("This is an info message");
								}
							}
							
output-log4j-java-selenium

Xml file configuration with Log4J

We can also configure the log4j logging system with xml configuration file. Please follow below steps to configure the log4j with xml.

xml-log4j-java-selenium-webdriver

1. All the attributes between &lappender> are appender component properties.
2. name: fileAppender and the value is Rolling file appender , which means use RollingFileAppender as output type.


												<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
											


3. name:File and value location of the file point to where to store the output.


											<param name="File" value="C:\\~\\firstXMLLog.log"/>
											


4. layout tag mention what kind of the layout we want in output (here patteren layout)


											<layout class="org.apache.log4j.PatternLayout">
										  


5. priority tag defines what is the priority level


											<priority value ="debug">
											




Integrate XML with Log4j



1. Create Java class under java project 2. Create object for logger class using getLogger() method from Logger class.

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


3. Load the xml file using confugure method from the DOMConfigurator class


											//DOMConfigurator is used to configure logger from xml configuration file
											DOMConfigurator.configure("C:\\~\\log4j.xml");
											


4. Log an message to the file


											//Log to file
											log.fatal("Log4j XML configuration is successful !!");
											

Complete program for XML integration with log4j

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class LOgWithXML
{
	static Logger log = Logger.getLogger(LOgWithXML.class);

	public static void main(String[] args)
	{
		//DOMConfigurator is used to configure logger from xml configuration file
		DOMConfigurator.configure("C:\\~\\log4j.xml");

		//Log to file
		log.fatal("Log4j XML configuration is successful !!");
	}
}
											
xml-output-log4j-java-selenium

Single Inheritance in Selenium and java

HTML Logging in Log4J

his layout outputs events in a HTML table. Appenders using this layout should have their encoding set to UTF-8 or UTF-16, otherwise events containing non ASCII characters could result in corrupted log files.


log4j-html.properties :

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

# Define the file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=C:\\~\\HTMLlog.html

# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=HTML log
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Threshold=DEBUG

HTMLLog.java :

package loggy;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HTMLLog {
	static Logger log = Logger.getLogger(FirstLog.class);
	public static void main(String[] args) {
		//PropertiesConfigurator is used to configure logger from properties file
        PropertyConfigurator.configure("C:\\~\\log4j-html.properties");
 
        //log the message to file
        log.trace("This is a trace message");
        log.info("This is an info message");
        log.warn("This is an warn message");
        log.error("This is an error message");
        log.fatal("This is an fatal message");
	}
}

Output :
html-log4j-java-selenium-webdriver

Advantages of Log4J

  • log4j is optimized for speed, the burden of logging is minimized.
  • log4j is thread-safe.
  • We can have logs in different format
  • log4j is not restricted to a predefined set of facilities.
  • log4j properties can be set at runtime
  • Supports XML and Properties files configuration
  • log4j can direct its output to a file, the console, a java.io.OutputStream, java.io.Writer, a remote server using TCP, a remote Unix Syslog daemon, to a remote listener using JMS, to the NT EventLog or even send e-mail.
  • log4j supports multiple output appenders per logger.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Registrations for Selenium Online Training is Over.

Below are the training details:
Meeting link : https://zoom.us/j/737840591
Starting Time : 9:00PM 18th DEC 2018
 
Join My Facebook Group
Join Group