WebDriver application example (java) - the test process uses Log4j to print logs

        The purpose of this instance is to use Log4j to print logs in a log file during testing for monitoring and subsequent debugging of the test script.

        Specific process:

        1. Download the Log4j package by yourself, log4j-1.2.17.zip is used here.

        2. Unzip the package and add the unzipped jar package to the Build Paht of the eclipse project.

        3. Create and set log4j.properties at the src level of the test code project, the contents are as follows:

### set up###
log4j.rootLogger = debug, D, E, info

### Output information to control lift ###
#log4j.appender.stdout = org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target = System.out
#log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### Output logs above DEBUG level to =F:\workspace\WebDriver API\log\\logerror.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = F://workspace/WebDriver API/log/loglog.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%p] %m%n
                                            

### Output logs above ERROR level to =F:\workspace\WebDriver API\log\\logerror.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =F://workspace/WebDriver API/log/logerror.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%p] %m%n


### Output logs above info level to =F:\workspace\WebDriver API\log\\loginfo.log ###
log4j.appender.info = org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.File =F://workspace/WebDriver API/log/loginfo.log
log4j.appender.info.Append = true
log4j.appender.info.Threshold = INFO
log4j.appender.info.layout = org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%p] %m%n

        Configuration specific analysis:

        (1), log4j.rootLogger = level, appenderName, appenderName, ...
           where level is the defined output level, below this level will not be output, the main levels are OFF, ALL, FATAL, ERROR, WARN, INFO, DEBUG or Custom level, if OFF is set, no information will be output, if ALL is set, all information will be output; the other 5 levels are FATAL>ERROR>WARN>INFO>DEBUG, if your lenel is set to INFO, then you cannot Output DEBUG information;
            appenderName specifies where the log information is output to, console, file, etc., and multiple output destinations can be specified at the same time.
        (2), log4j.appender, this must also be configured, it is responsible for controlling the output of the logging operation. Its definition format is as follows:
            log4j.appender.appenderName=someAppender (select an output platform)
            log4j.appender.appenderName.File=file name] (file output definition path)
            log4j.appender.appenderName.layout=output layout
            log4j.appender .appenderName.layout.ConversionPattern=output format

        where log4j.appender.appenderName specifies the output appender, and Log4J provides several appenders:
        a), org.apache.log4j.ConsoleAppender (console)
        b), org.apache.log4j.FileAppender (file)
        c), org.apache.log4j.DailyRollingFileAppender (generates a log file every day)
    d), org.apache .log4j.RollingFileAppender (when the file size reaches the specified size, a new file is generated, the file size can be set by log4j.appender.R.MaxFileSize=100KB, and a backup can also be set by log4j.appender.R.MaxBackupIndex=1 document).
        e), org.apache.log4j.WriterAppender (send log information to any specified place in stream format)

        log4j.appender.appenderName.layout specifies the format (layout) Layout of log information, which is responsible for formatting the output of Appender. The layouts provided by Log4j are as follows:
        org.apache.log4j.HTMLLayout (layout in HTML form)
        org.apache.log4j.PatternLayout (layout mode can be flexibly specified)
        org.apache.log4j.SimpleLayout (contain log information level and information string)
        org.apache.log4j.TTCCLayout (contains log generation time, thread, category, etc.).

log4j.appender.appenderName.layout.ConversionPattern formats log information. Log4J uses a print format similar to the printf function in C language to format log information. The printing parameters are as follows:
        %m The message specified in the output code
        %p The output priority, that is DEBUG, INFO, WARN, ERROR, FATAL
        %r Output the number of milliseconds it takes to output the log information from the application startup to outputting the log information
        %c Output the category to which it belongs, usually the full name of the class it belongs to
        %t Output the thread name that generated the log event
        % n Output a carriage return line feed, "rn" for Windows platform, "n" for Unix platform
      %d Output the date or time of the log time point, the default format is ISO8601, you can also specify the format after it, for example: %d{ yyyy MMM dd HH:mm:ss,SSS}, the output is similar: June 24, 2012 23:55:28, 92
        %l Output the location of the log event, including the category name, the thread where it occurred, and in the code number of rows.

        (3), log4j.logger
        is not required. If this is not configured, the level of log4j.rootLogger is used. It is mainly specific to package and class level info, and its definition format is as follows:
        log4j.logger.packageName[.ClassName]=level[,appender]

        It can also output to the specified appender, or not specify the output to the default appender.


        4. Define a Log tool class as follows:

package cn.om.log4j;

import org.apache.log4j.Logger;

public class Log {
	//Initialize a logger object
    private static Logger Log=Logger.getLogger(Log.class);
    public static void startTestCase(String sTestCaseName){
    	Log.info("-----------------------------------------------");
    	Log.info("***********                "+sTestCaseName+"    *************");
    }
    
    //Define a static method that can print the log information of the end execution of a custom test case
    public static void endTestCase(String sTestCaseName){
    	Log.info("*********** "+"End of test case execution"+" ***********");
    	Log.info("-----------------------------------------------");
    }

    //Define a static info method to print custom info level log information
    public static void info(String message){
    	Log.info(message);
    }
    
    //Define a static warn method to print custom warn level log information
    public static void warn(String message){
    	Log.warn(message);
    }
    
    //Define a static error method to print custom error level log information
    public static void error(String message){
    	Log.error(message);
    }
    
    //Define a static fatal method to print custom fatal level log information
    public static void fatal(String message){
    	Log.fatal(message);
	}
    
    //Define a static debug method to print custom debug level log information
    public static void debug(String message){
    	Log.debug(message);
    }
}

        5. Create a test class TestSearch with the following contents:

package cn.om.log4j;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;

public class TestSearch {

	WebDriver driver;
	String url = "http://www.sogou.com";

	@Test
	public void testSearch() {
		Log.startTestCase("Search");
		driver.get(url);
		//Print the log information of "open sogou home page"
		Log.info("Open sogou home page");
		//Enter "Road to Glory Automated Tests" in the search box
		driver.findElement(By.id("query")).sendKeys("Road to Glory Automated Test");
		Log.info("Enter the search keyword "Road to Glory Automated Test"");
		//Click the "Search" button
		driver.findElement(By.id("stb")).click();
		//Print the log information of "click the search button"
		Log.info("Click the search button");
		Log.error("Error");
		/ / Print the log information of the end of the search test case execution to the log file
		Log.endTestCase("Search");
	}

	@BeforeMethod
	public void beforeMethod() {
		System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		url = "http://www.sogou.com";
	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}
}

        The priority of log information is ERROR, WARN, INFO, DEBUG from high to low, which is used to mark the importance of this log. Log4j supports two configuration file formats, one is XML format and the other is java feature file (that is, the format of this article). The xml file format is not introduced separately.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770887&siteId=291194637