在自動化測試腳本的執行過程當中,使用log4j在日誌文件中打印執行日誌,用於監控和後續調試腳本。web
Log4j.xml 文件chrome
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <!-- 日誌輸出到文件 --> <appender name="fileAppender" class="org.apache.log4j.FileAppender"> <param name="Threshold" value="INFO" /> <!-- 輸出的日誌文件名 --> <param name="File" value="logfile.log" /> <!-- 設置日誌輸出的樣式 -->` <layout class="org.apache.log4j.PatternLayout"> <!-- 日誌輸出格式 --> <param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" /> </layout> </appender> <root> <!-- 設置日誌級別 --> <level value="INFO" /> <appender-ref ref="fileAppender" /> </root> </log4j:configuration>
Log工具類apache
import org.apache.log4j.Logger; public class Log { // 初始化Log4j日誌 private static Logger Log = Logger.getLogger(Log.class.getName()); // 打印測試用例開頭的日誌 public static void startTestCase(String sTestCaseName) { Log.info("------------------ " + sTestCaseName + " " +"開始執行 ------------------"); } //打印測試用例結束的日誌 public static void endTestCase(String sTestCaseName) { Log.info("------------------ " + sTestCaseName + " " +"測試執行結束 ---------------"); } public static void info(String message) { Log.info(message); } public static void warn(String message) { Log.warn(message); } public static void error(String message) { Log.error(message); } public static void fatal(String message) { Log.fatal(message); } public static void debug(String message) { Log.debug(message); } }
測試代碼app
import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Log4jTest { WebDriver driver; @BeforeMethod public void beforeMethod(){ System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe"); driver = new ChromeDriver(); } @AfterMethod public void afterMethod(){ driver.quit(); } @BeforeClass public void beforeClass(){ DOMConfigurator.configure("log4j.xml"); } @Test public void test(){ String url = "http://www.baidu.com"; Log.startTestCase("搜索功能"); driver.get(url); Log.info("打開百度首頁"); driver.findElement(By.id("kw")).sendKeys("selenium"); Log.info("輸入搜索關鍵字'selenium'"); driver.findElement(By.id("su")).click(); Log.info("單擊搜索按鈕"); Log.endTestCase("搜索功能"); } }
輸出的日誌文件以下:工具
2019-05-14 22:36:53,100 INFO [Log] ------------------ 搜索功能 開始執行 ------------------
2019-05-14 22:36:58,747 INFO [Log] 打開百度首頁
2019-05-14 22:36:58,943 INFO [Log] 輸入搜索關鍵字'selenium'
2019-05-14 22:36:59,050 INFO [Log] 單擊搜索按鈕
2019-05-14 22:36:59,050 INFO [Log] ------------------ 搜索功能 測試執行結束 ---------------測試