Advance Reporting, Advance Selenium

how to create log files in selenium webdriver using Log4J

Hello welcome to Selenium Tutorials, in this post we will see how to create log files in selenium webdriver

In Automation, reporting plays an important role so we can generate the different type of HTML reports, XSLT report, Log files etc.

 

If you want to create enhanced report and with log attached to HTML report you can use extent report (I use this report) as well 

 

Here is the YouTube video for the same

 What is Log File?

The log file is a just simple file, which keeps track of the record or event or info when any event happens or any software run. This whole process is known as logging. We can create a log file as simple log file as well as HTML format.

 

Note- Any file whose extension is .log will be considered.

 

Sample Log file
1- Simple log file in text format

log file in Selenium

log file in Selenium

 

2- Log files in HTML format

 

how to create log files in selenium

how to create log files in selenium

Why is it required in Selenium?

We can create a log file for our simple script also so we can track or debug our script easily if anything goes wrong in the script. For example, if our script is failing at some point then we can track back what went wrong.

 

What is log4J- Log4j is free open source tool given by Apache foundation for creating log files It helps us to generate a log file in various output target.

How to create log files in selenium

Step 1- Download log4j jar file

Click on the link to download http://mirrors.ibiblio.org/pub/mirrors/maven/log4j/jars/log4j-1.2.15.jar

 

Step 2- Add log4j to your current project

Select your project > Right click > Click on build path> Click Configure build path> Go to library section > Add external jar file > select the log4j > click on save

 

Step 3- Open notepad and copy the below code and save the file as log4j.properties.

Note- Please create the log folder inside home directory and while saving use “” to save file

 

// Here we have defined root logger
log4j.rootLogger=INFO,CONSOLE,R,HTML,TTCC

// Here we define the appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.TTCC=org.apache.log4j.RollingFileAppender
log4j.appender.HTML=org.apache.log4j.FileAppender

// Here we define log file location
log4j.appender.R.File=./log/testlog.log
log4j.appender.TTCC.File=./log/testlog1.log
log4j.appender.HTML.File=./log/application.html

// Here we define the layout and pattern
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %5p [%t] (%F:%L)- %m%n
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n
log4j.appender.TTCC.layout=org.apache.log4j.TTCCLayout
log4j.appender.TTCC.layout.DateFormat=ISO8601
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true

Once you save file it will look like

 

how to create log files in selenium

how to create log files in selenium

 

Step 4- Write test case

import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Google {
    public static void main(String[] args) {
      
    // Here we need to create logger instance so we need to pass Class name for 
     //which  we want to create log file in my case Google is classname
         Logger logger=Logger.getLogger("Google");
        

       // configure log4j properties file
       PropertyConfigurator.configure("Log4j.properties");


        // Open browser
        WebDriver driver = new FirefoxDriver();
        logger.info("Browser Opened");
      
        // Set implicit wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        logger.info("Implicit wait given");
      

        // Load application
        driver.get("https://www.google.co.in/");
        logger.info("Url opened");
      

        // type Selenium
        driver.findElement(By.name("q")).sendKeys("Selenium");
        logger.info("keyword type");           
    }
}

 

Step 5- Execute  your test case and verify the output and log files as well

Finally, here are three different log files.

 

how to create log files in selenium

how to create log files in selenium

 

Kindly Share this post with more friends and Spread the Knowledge 

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

77 thoughts on “how to create log files in selenium webdriver using Log4J

  1. Pankaj says:

    Hi Mukesh,
    good ,i am beginner is selenium but you explain very well about loggers. My question is that can we make excel file of log instead of normal text file??

    1. Hi excel is preferred for test data not for logs.

  2. saran says:

    Hi Mukesh Sir,

    Will the above steps in “How to create log files in selenium” will solve in linux machine ??

    1. Hi Saran,

      Yes, this will work in linux environment too.

  3. Rajesh says:

    Hi Mukesh,

    Is it possible to catch test steps, results into log file without calling log in test steps

    1. Hi Rajesh,

      Yes, it is possible using Listeners. You can use either TestNG listeners or WebDriverEventListener or both as per your required granularity.

  4. Hare Krishna says:

    I left the same comment under your video about how to generate log files. In case you see this first please help.

    Mukesh, thank you a lot. I am learning like in a good school from you. Would you know how to add clickable line # in Intelije? I used the same and tried other log4j file content and I am getting this:

    0 [main] INFO RandomPractice – Google is launched
    17 [main] INFO RandomPractice – Search field is located
    143 [main] INFO RandomPractice – Hare Krishna is entered
    2126 [main] WARN RandomPractice – Searching for the entered text

    Whereas I am aiming for getting what you have in the video. I ‘ve heard Inlelije works differently. I have my “log4j.properties” file, may be you can advise what I can add to get the clickable line # or may be there is another way. So far after going to so many blogs, I haven’t figured that out. Thank you very much. All the best to you!

  5. nikita says:

    contents are not overriding

    1. Hi Nikita,

      Kindly use log4j.appender.S.Append=false in log properties file

  6. Sourabh says:

    I have implemented this and its working fine but I want to override the existing log file whenever I run the code but currently it appends the new logs in the previous log file

    1. Hi Sourabh,

      Add log4j.appender.LOGFILE.Append=false into your log4j.properties and let me know.

  7. suyash says:

    Hi,
    I am getting this
    log4j:ERROR Ignoring configuration file [Log4j.properties].
    log4j:WARN No appenders could be found for logger
    log4j:WARN Please initialize the log4j system properly.

    1. Hi Suyush,

      These messages come because log4j has not been implemented fully. As of now, it is fine. Just check whether you are getting logs properly or not…

    2. Hare Krishna says:

      Add this line and the issue will be fixed:

      BasicConfigurator.configure();

    3. Priya says:

      Place log4j.properties file under resources folder.

  8. divya says:

    Hai Mukesh,
    Im starter in automation selenium, ur posts are very useful for step by step procedure..Thanks for ur effort..

    1. Hi Divya,

      Thanks for your appreciation.

  9. Debanjan Bhattacharjee says:

    Wonderful Video Article on Log generation in Selenium. Thanks a ton !!!

    1. Thanks Debanjan 🙂 I am glad you liked all concepts.

  10. Sanjay Pradhan says:

    Very helpful and easy to follow.
    Thanks so much!!!

    1. Hi Sanjay,

      I am happy to see that my post helped you to implement your requirement.

  11. shalaka says:

    Hi Mukesh,
    Very helpful post for generating logs. I have a question that when the code in eclipse is big enough, it is tedious job to write logger.info(“”); statement after every line. Is there a way out?

    1. Hi Shalaka,

      As of now this is the real way to implement log file. For your simplicity, create a method which accepts arguments for logging as parameter.

  12. falak garg says:

    hey mukesh..
    how can i do logging in selenium webdriver using python binding?

    1. Hi Falak,

      I never worked much in python. Apologies for not helping you.

  13. Nikhil says:

    Mukesh how do we configure properties file for Log4j, because it varies for project to project. Is there any site we can learn from

    1. Hi Nikhil,

      Could you please explain your scenario.

  14. Nirupa says:

    Hi,
    How to resolve the error:” Unable to instantiate the class[org.apche.log4j.patternLayout]”

  15. chandrika says:

    Hi Mukesh.

    I have tried to generate logs its generating in console only not into file.
    When i tried to save save log4j.properties file with double quotes its saved as log4j.properties not like log4j.
    Please help me in this.

  16. siva says:

    Hello Mukesh sir,

    How to use debug,fatal,error,warn methods in log4j.

    1. Hi Siva,

      you can use in below manner

      logger.info(“Url opened”);
      logger.debug(“Url opened”);
      logger.error(“Url opened”);

  17. Nikhil says:

    Mukesh very good explananation. How do we learn how to configure log4j properties file?

    Also what is this line meaning – PropertyConfigurator.configure(“Log4j.properties”);

    1. It means we are specifying the file where all settings are defined.

  18. Pratikshya says:

    Hi Mukesh

    Very nice Explanation. Thank you . I have one doubt . I have used Logger.info in my selenium script and it works fine when I run in local eclipse. But when I run the same program in jenkins , it gives warning for Logger File. Why the same Logger configuration didnt work in Jenkins ?

    1. Hi Pratikshya,

      Ideally it should not give any warning. Have you tried with advance report https://vistasadprojects.com/mukeshotwani-blogs-v2/advance-selenium-reporting-with-screenshots-2/

  19. suresh says:

    hi mukesh,

    I am using extent report with attach screenshot but how can I specify the path of failure screenshot.
    screenshot like gmail.08082016121213.png
    it will be generating at failure time and how, I want to take that one’s path as specify in report path

  20. Ajay Somni says:

    Hi Mukesh, Thanks for your valued contribution to the tech community.
    Kindly provide a tutorial on new backlog. Thanks

    1. Hi Ajay,

      Thanks . Can you please explain for more about backlog tutorial ?

      1. Ajay Somni says:

        Sorry it was LogBack logger….
        http://logback.qos.ch/

  21. ganesh says:

    how can i append the error code in exception block to the log file. logger.info is not working in catch block.

  22. ganesh says:

    how to generate a new report every time when i run a program because its showing all previous reports.

    1. Hi ganesh,

      use extent report in this case.

  23. Sireesha says:

    Where we have to copy the file? what is home directory?

    1. Hi Sireesha,

      Home directory mean where project resides.

      To get home directory Right click on project > Click on properties > get the location

  24. Prasanna says:

    I want to genrate seprate log files for these indepent pice of code

  25. Ratna says:

    Explained very well. Excellent teaching method.
    Thank you so much for sharing.

    1. Thank you Ratna 🙂

  26. Siddharth says:

    Hi Mukesh

    Right now I am unable to download the log4j jar file from the above mentioned url given by you.

    Can you please check this once.

    1. Hi Sid,

      Thank you for correcting. Please find below link for jar

      https://logging.apache.org/log4j/1.2/download.html

      I would recommend for extent report which create advance logs https://www.youtube.com/watch?v=dBj7pxhZXhY

  27. pooja says:

    very helpful videoas . thanks a lot . please can you explain about how to automate when the images in the application keeps moving.” http://store.demoqa.com/” website link

    1. Hi Pooja,

      Thank you.

      Can u please explain your requirement in brief? Do u want to check the image presence or url of images ?

  28. rahul says:

    awesome Explanation …….

  29. Prabhakar Reddy Gollapudi says:

    Hi Mukesh,
    I am following you from last 2 weeks and i found your blog very useful,completely different from other one.
    Keep posting new things and make the people know more 😛

    1. HI Prabhakar,

      Thank you so much. Keep visiting I have so many post in pipeline.

  30. Sandeep says:

    Where do you save the log4j.properties, i mean what folder does this needs to be saved to

  31. shubham says:

    Thanks it worked for me…able to see logs for console,text and html.

  32. yaswanth says:

    HI Mukesh I want to store the logs in excel file .please tell me how to do this.

    1. Hi Yeswanth,

      I will suggest you not use excel for logs.

  33. Rajiv says:

    Hello Mukesh,

    I am using maven and try to save the log results in log file. Results are printing on console but not same in log files files: Following is the console out put.
    ————————————————————–
    Dec 10, 2015 11:58:13 AM pageTests.log4j main
    INFO: Browser Opened
    Dec 10, 2015 11:58:25 AM pageTests.log4j main
    INFO: Implicit wait given
    Dec 10, 2015 11:58:25 AM pageTests.log4j main
    INFO: Url opened
    Dec 10, 2015 11:58:28 AM pageTests.log4j main
    INFO: keyword type
    —————————————————————-

    How can I save logs under log file in maven. I have log4j included dependencies in pom.xml file.


    Rajiv

    1. Hi Rajiv,

      Can u please share the log4j property then I can check the exact issue.

      I would recommend to use extent report which have log with report itself.

      Give a try https://vistasadprojects.com/mukeshotwani-blogs-v2/advance-selenium-reporting-with-screenshots-part-2/

  34. Matt W says:

    How can I catch an error using this. I’m hitting or using the Firefox driver with C#. What is happening for me is that my tests run successfully in Visual Studio or from a command line outside of our TFS Build process, but during the build, the same test case keeps failing. I’m able to capture a screenshot on error, but it isn’t very helpful.

    I’d like to see if a control can’t be found, it times out, etc. Would this be the tool for me.

    Any help to catch errors in the log if this tool will work for me would be greatly appreciated!!

    1. Hi Matt,

      I have not worked on C# so not sure can you please check below link http://www.toolsqa.com/selenium-webdriver-tutorials-in-c-selenium-tutorial-in-c/

  35. premkumar says:

    its works thanks a ton MUKESH OTWANI

    1. Great Cheers Prem 🙂

  36. AthenaTietjen9 says:

    Hi there, just became aware of your blog through Google, and found that it is really informative. I’m going to watch out for brussels. I’ll be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers!

    1. Thank you 🙂 Yes will continue with the same.

  37. TyreeKeener28 says:

    Nice post. I was checking continuously this blog and I am impressed! Extremely useful info particularly the last part 🙂 I care for such information much. I was seeking this certain information for a long time. Thank you and best of luck.

Leave a Reply

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

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