How to write Log into log file in Selenium webdriver using java.


Components:
1. Instance of Logger class with below mention methods.
error, warn, info, debug, log

Configuration:
1. Download "log4j-1.2.17.zip" file from Here and unzipe, add "log4j-1.2.17.jar" file into your desired java project.
2. Add a New XML file, name is "configure_logfile.xml" with under properties in your desired java project Home_directory.





   
                                              
Source Code:
 import org.apache.log4j.LogManager;  
 import org.apache.log4j.Logger;  
 import org.apache.log4j.xml.DOMConfigurator;  
   
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.*;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
   
 public class Writelogintofile {  
     
 static final Logger logger = LogManager.getLogger(Writelogintofile.class.getName());  
     
 public static void main(String[] args) {  
   
 DOMConfigurator.configure("configure_logfile.xml");  
 logger.info("============================================ ");  
 logger.info("Log has started to write");  
 //create Firefox instance  
 WebDriver driver = new FirefoxDriver();  
 logger.info("create Firefox instance");  
 //Puts a Implicit wait, Will wait for 10 seconds before throwing exception  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
   
 //Launch website  
 driver.navigate().to("http://www.google.com/");  
 logger.info("Open Google Website");  
   
 //Maximize the browser  
 driver.manage().window().maximize();  
 logger.info("Maximize the browser");  
   
 //Click on Gmail  
 driver.findElement(By.linkText("Gmail")).click();  
 logger.info("Clicked Gmail Link");  
   
 // Back previos state   
 driver.navigate().back();  
 logger.info("Backed Google from gmail");  
 // Forwart previos state   
 driver.navigate().forward();  
 logger.info("Forwared Google to gmail");  
 //Navigate to facebook   
 driver.get("http://www.facebook.com/");  
 logger.info("Navigated to facebook ");  
   
 if (driver.getTitle().trim().equals("Google")) {  
   logger.info("The Result is Pass");  
 } else {  
   logger.error("TEST FAILED. NEEDS INVESTIGATION");  
 }  
 logger.warn("May be condition is not fullfill");  
   
 //Close the Browser.  
 driver.close();  
 logger.info("============================================ ");  
   }  
 }  
   
   
Output: After execution, "write_log.log" file is created on the root folder with below output

No comments:

Post a Comment