Complete Log4j Uses in Java project with an example
Current usages indicate that logging has become an important component of development and testing life cycles and for this purpose, we are going to discuss the optimal use of Log4j in Java. If you want to learn more about basic Java then read Java Tutorial
Advantages of logging
- gives a fair understanding of application run
- log output can be saved into some external medium and can be studied later on
- helps in debugging the issues in case of test automation failures
- can also be used for auditing by the project/product stakeholders to look at the application’s health
So logging can be achieved by using any of the open-source java API’s available for logging or one can create his/her utility for that matter of fact.
As we are more intended towards testing, thus we will precisely talk in the same context.
Like I said above, there are various utilities available for generating logs. Few amongst the large chunk are:
– File Logging (Selenium IDE)
- A freshly introduced plug-in for Selenium-IDE to save logs to a file
- This plug-in, for Selenium-IDE, saves log messages to a file in real-time at a user-selectable log level and location. Like Selenium IDE, it is a firefox plug-in and can be seen as one of the tabs in Selenium IDE upon installation.
– JUL – Java util logging
- It is a java logging API to generate/save logs.
– Log4j – A popular logging package for Java
Let us study logging in detail using log4j. To begin with the history of log4j, Secure Electronic Marketplace for Europe decided to create a logging API in early 1996. Eventually, their efforts paid off and hence log4j was evolved. Log4j is distributed under the IBM Public License and is an open-source package.
Components of Log4j
- Loggers
- Appenders
- Layouts
All the above three components are equally responsible for making us generate the logs depending on the level type, formats of the log messages and where they would be saved. Starting with the loggers, let’s discuss each of them first before moving on to the actual implementation.
Loggers
Logs can be generated using two essentials components:
- An instance of Logger class
- Log level (printing methods) – used for printing the log messages. Levels are of the following kinds:
- error()
- warn()
- info()
- debug()
- log()
These printing methods are invoked on the Logger instance as and when we need to print the log messages. An unclouded picture would be shown later in the blog while implementation.
Appenders
Appenders are used when we desire to generate our logs at different persistent mediums. These mediums can range from Console to external files to GUI Components etc. Thus, appenders enable us to refer these logs later on.
There are no. of appenders available with a specific output mechanism. Log4j allows us to use multiple appenders at the same time. Thus unlike using single appender, one can use more than one kind of appender to fulfil his/her logging requirements.
Layouts
Layouts help us to customize the way log4j would be rendering log messages to us. Thus we can associate each of the appenders with a specific layout enriching the format of the log messages generated according to our wish.
As there can be multiple appenders, similarly we can have multiple layouts too. In other words, we can say that we can associate a specific appender with a specific layout pattern and so on.
Thus, we get log messages in a desired format and location.
Now that we are done with most of the theory part, it’s time to do some implementation.
To make it more comprehensible, we will discuss the implementation step by step.
Installation/Setup
I am assuming that you all already have a fair understanding of eclipse and selenium webdriver and have a setup already in place. For those who aren’t yet familiar with eclipse and selenium, this implementation would not be of much use. So I would request you to first read about Selenium Webdriver. Refer this for more details on Selenium.
Step1. The package distribution is widely available. Thus, download the latest version of log4j jar from here.
Step2. In eclipse, configure build path and add log4j.jar as an external jar. Refer the following figure:
Configuration
Inserting log messages into the application code requires a fair amount of planning and effort.
There are two ways to configure log4j:
- Programmatically
- Using configuration files
log4j can be configured programmatically. However, configuring log4j using configuration file seems to be an easy and better option. Configuration files are nothing but XML files constituted of various artefacts.
Sample Configuration File
Step1. Create a log4j.xml file
<!--DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <!-- For Printing message with date , time & class name also -->
Components of Configuration File
– consoleAppender
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout">
- Console appender is used to print the log messages on to the console.
- fileAppender
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
- File appender is used to print the log messages into a file.
<param name="append" value="false"/>
- The append value can be set to either “false” or “true”.
- false – The parameter overwrites the logs created previously with the one created in the current run.
- true – The parameter appends the logs of the current run with the previously created logs.
<param name="file" value="Logs/Webliv_Automation_Logs.log"/>
- This parameter is used to instruct the location with respect to the root folder and name of the log file.
- roll
<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
- DailyRollingFileAppender extends FileAppender. It rolls the file over a specified period and frequency.
- The rolling schedule is specified by the DatePattern option. This pattern should follow the SimpleDateFormat conventions.
- It is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules.
– layout
<layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{dd-MM-yyyy HH:mm:ss}%x %-5p[%c{1}]: %m%n"/> </layout>
- The PatternLayout is a part of the standard log4j distribution. It lets the user specify the output format with the help of conversion pattern.
For Ex.”%d{dd-MM-yyyy HH:mm:ss}%x %-5p[%c{1}]: %m%n”
Output
30-01-2014 15:08:58 INFO [Demo]: Sample log message
In the output above:
- The first field represents the date of execution
- The second field represents the time when the log message was printed
- The third field represents the log level
- The fourth field represents the thread making the log request
- The fifth field represents the actual log message
Step2. Place the log4j.xml file into the project root folder.
Implementation
Step1. Here, the below example demonstrates “testsuite.java” to instruct “DOMConfigurator” to parse the configuration file “log4j.xml” and setup logging.
Syntax:
package com.logExample; import org.apache.log4j.xml.DOMConfigurator; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runners.Suite; /** * @author Shruti Shrivastava * */ @RunWith(Suite.class) @Suite.SuiteClasses({ Demo.class }) public class TestSuite { /** * Setup method to set system property for log file name */ @BeforeClass public static void Setup() { // loading log4j.xml file DOMConfigurator.configure("log4j.xml"); } /** * @param args */ public static void main(String[] args) { Result result = JUnitCore.runClasses(TestSuite.class); for (Failure failure : result.getFailures()) { System.out.println("nTEST NAME: " + failure.getTestHeader()); System.out.println("nERROR: " + failure.getMessage() + "n"); System.out.println(failure.getTrace()); System.exit(1); } } }
Step2. Create a test class “Demo.java” in the project hierarchy under eclipse.
Step3. Import Logger.
Syntax:
import org.apache.log4j.Logger;
Step4. Initialization of Logger Instance.
Step5. Using log variable for printing the log messages across the class.
// Object initialization for log
static Logger log = Logger.getLogger(Demo.class.getName());
try{
// Upload the file to test
newFilename = preTestObj.uploadFile(toolsObj.getTestFilePath(), data.getExtraElement().get(0), "Test file to upload.",
log.info("Uploaded the file to System:"+filename);
// Submit the changes
log.info("Submitting the changes");
driver.findElement(By.xpath(".//*[@id='loadingmask']/div[3]/div[2]/input[1]")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
Thread.sleep(3000);
}
catch (Exception e) {
e.printStackTrace();
log.error("ComMessages.getString(ExceptionMessages.DUPLICATE_FILE, newFilename)");
throw new WeblivException(ComMessages.getString(ExceptionMessages.DUPLICATE_FILE, newFilename));
}
Output
The log file would be generated at the root folder within the folder named as Logs. Refer
The output generated is:
29-01-2014 15:08:22 INFO [Demo]: Uploaded the file to the System: FileExample.txt
29-01-2014 15:08:22 INFO [Demo]: Submitting the changes
29-01-2014 15:08:23 ERROR [Demo]: The File uploaded seems to be a duplicate file.
Conclusion
With so many advantages, log4j has become the most voted choice for logging. User is served with the choice of logs format and location. It’s widely said that logging incurs the performance cost on the overall system, so log4j is so designed that additional log statements do not incur a heavy performance cost.
Reference:
For more information on logging read this
Thats a very nice post …Keep writing.. Is there any way in which we can implement default Log for my code..? If found something please let me know.
Thank yo so much Vishwas…what do you mean by default log??
Hi Shruti,
In my selenium project can we use this log4j with testng frame work also
there we have a test case class and base class (containing set up and tear down method)
Hello Amit,
Yes, you can use log4j. This utility is independent of the type of underlined framework and its works perfectly fine with TestNG.
Regards,
Shruti
Hi Shruti,
form this topic “Configuration of Log4j in java project with example”
here am able to view the topic content but unable to view the images like (log4j-5, log4j-2, log4j-3).
if i click on image it navigates to URL: and shows below message
“WordPress.com
— 403: Access Denied —
This file requires authorization:
You must be logged in
and a member of this blog.
Log in to proceed.
You can create your own free blog on WordPress.com.”
> for this i have registered in wordpress but still not able to view the image.
>> Could you plz look into once? and guide the resolution to view the images.
Regards,
Surya
Thank you Surya for letting us know this credential related problem to view some images on website.
We are working on it and might be next time you would be able to see the proper image without any problem.One more request if you are facing the same problem with any other post then please let us know
Thank you!!
This post really helped me because it exactly tells me where you have to load your log4j.xml file.