Selenium 简明教程

Selenium - Log4j Logging

Selenium Webdriver 可用于记录测试执行期间的信息。记录主要用于提取有关执行如何发生的信息。

Selenium Webdriver can be used for logging information during test execution. The logging is mainly used to extract information about how the execution took place.

记录通过提供有关应用程序功能(正常工作或不正常工作)的数据来帮助增强任何应用程序。因此,记录对于提高应用程序质量和解决问题非常重要。

Logging helps to enhance any application by supplying data on the features of the application which are working or not working. Thus logging is important to raise the quality of the application and troubleshoot issues.

What is Log4j?

Log4j 是一个基于 Java 的开源框架,主要用于记录信息。这是一个直接、健壮、快速的框架。Log4j 必须使用配置文件进行配置,形式是键值对,比如 Log4j.xml 文件、Log4j.properties 文件、yaml 或 JSON 文件等。Log4 是 Apache Logging Services 的一部分。

Log4j is an open-source Java based framework primarily used for logging information. It is a straightforward, sound, and fast framework. The Log4j has to be configured using a configuration file like Log4j.xml file, Log4j.properties file, yaml or JSON file, and so on in the form of key value pairs. Log4 is a part of Apache Logging Services.

Components of Log4j

Log4j 的组件如下所列 −

The components of Log4j are listed below −

  1. Loggers

  2. Appenders

  3. Layouts

Loggers

The Loggers 包含使用 Log4j 框架产生的所有重要日志信息。Loggers 的基本组件是 −

The Loggers contain all the important logging information produced by using the Log4j framework. The basic components of Loggers are −

  1. Object of Logger class.

  2. Log Levels − The log levels help to get the log messages. The log levels are - ALL which logs all every information, ERROR which logs only error information which may pause the execution, WARN which logs only error information which may pause the execution but not fatal, DEBUG which logs information required for debugging, INFO which logs how the application is responding, TRACE which logs the most elaborate logging information, and FATAL which logs picky information of the application which may result in crash in the application.

Appenders

附加器从 Loggers 获取信息并将其输出到其他文件或存储。附加器包括 - FileAppender 将日志信息写入另一个文件, RollingFileAppender 与 FileAppender 类似,但对文件大小有限制,一旦文件大小超过限制,附加器创建另一个新文件来捕获剩余的日志信息, DailyRollingFileAppender 用于提供将日志信息捕获到文件的间隔,以及 ConsoleAppender 将日志信息写入控制台。

The appenders get the information from the Loggers and outputs it to another file or storage. The appenders are - FileAppender which writes the logging information to another file, RollingFileAppender which works similar to FileAppender with limit to the file size, once the file size exceeds, the remaining logging information is captured in another new file created by the appender, DailyRollingFileAppender is used to provide the interval in which logging information is to be captured in a file, and ConsoleAppender which writes the logging information in the console.

Layout

布局用于设置日志文件的格式。布局包括 - Pattern Layout、HTML Layout、XML Layout等等。

The layouts are used to set the format of the log files. The layouts are - Pattern Layout, HTML Layout, XML Layout, and so on.

Prerequisites for Log4j Logging

  1. Install Java(version above 8) in the system and check if it is present with the command: java -version. The java version installed will be visible if installation has been completed successfully.

  2. Install maven in the system and check if it is present with the command: mvn -version. The maven version installed will be visible if installation has been completed successfully.

  3. Install any IDE like Eclipse, IntelliJ, and so on.

  4. Save the pom.xml with all the dependencies and update the maven project

Steps for Log4j Logging

Step 1 − 创建一个 Maven 项目并将适当的依赖项添加到 pom.xml 文件中,用于以下项 −

Step 1 − Create a maven project and add the proper dependencies to the pom.xml file for the below items −

  1. Add Log4j dependencies from the below link: https://logging.apache.org/log4j/.

  2. Add the Selenium Java dependencies from the link: https://mvnrepository.com/artifact/.

  3. Save the pom.xml with all the dependencies and update the maven project.

Step 2 − 创建一个配置文件 - log4j.xml 或 loj4j.properties 文件。在这里,我们将提供设置。在我们的项目中,我们已在 resources 文件夹下创建了一个名为 log4j2.properties 的文件。

Step 2 − Create a configuration file - log4j.xml or loj4j.properties file. Here, we will provide the settings. In our project, we had created a file named log4j2.properties file under the resources folder.

selenium log4j logging 1

Step 3 − 创建一个测试类,在其中我们将创建一个 Logger 类的对象并纳入日志语句。运行该项目并验证结果。

Step 3 − Create a test class where we will create an object of the Logger class and incorporate the log statements. Run the project and validate the results.

Example

package Logs;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LoggingsInfo {

   // object of Logger class
   private static Logger logger = LogManager.getLogger(LoggingsInfo.class);

   public  static void main(String args[]){

      System.out.println("Execution started: ");

      // logging messages
      logger.info("This is for information");
      logger.error("This is for error information");
      logger.warn("This is for warning information");
      logger.fatal("This is for fatal information");

      System.out.println("Execution done: ");
   }
}

log4j2.properties 文件中的配置。

Configurations in log4j2.properties file.

name=PropertiesConfig
property.filename = logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/LogsGenerated.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=Logs
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

pom.xml 中的依赖项。

Dependencies in pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>

      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

      <dependency>
         <groupId>org.apache.logging.log4j</groupId>
         <artifactId>log4j-api</artifactId>
         <version>2.23.1</version>
      </dependency>

      <dependency>
         <groupId>org.apache.logging.log4j</groupId>
         <artifactId>log4j-core</artifactId>
         <version>2.23.1</version>
      </dependency>

   </dependencies>
</project>

Output

Execution started:
[INFO ] 2024-03-21 16:15:08.431 [main] LoggingsInfo - This is for information
[ERROR] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for error information
[WARN ] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for warning information
[FATAL] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for fatal information
Execution done:

Process finished with exit code 0

此外,一个文件 LogsGenerated.log 将在项目中的 log 文件夹内生成,其中包含作为控制台输出的日志信息。

Along with that a file LogsGenerated.log get generated within the log folder within the project containing the logging information as the console output.

selenium log4j logging 2

我们还可以通过更新 log4j2.properties 文件中的 rootLogger.level = tracelogger.file.level = trace 来更改日志级别配置以进行跟踪。

We can also change the logging level configuration to trace by updating the rootLogger.level = trace and logger.file.level = trace in the log4j2.properties file.

Updated configuration log4j2.properties

Updated configuration log4j2.properties

name=PropertiesConfig
property.filename = logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/LogsGenerated.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=Logs
logger.file.level = trace
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = trace
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Example

package Logs;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LoggingsInfo {

   // object of Logger class
   private static Logger logger =
   LogManager.getLogger(LoggingsInfo.class);

   public  static void main(String args[]){
      System.out.println("Execution started: ");

      // logging messages
      logger.trace("This is for trace information");
      logger.info("This is for information");
      logger.error("This is for error information");
      logger.warn("This is for warning information");
      logger.fatal("This is for fatal information");

      System.out.println("Execution done: ");
   }
}

Output

[TRACE] 2024-03-21 16:25:08.354 [main] LoggingsInfo - This is for trace information
[INFO ] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for information
[ERROR] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for error information
[WARN ] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for warning information
[FATAL] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for fatal information
Execution done:

Process finished with exit code 0

此外,项目中日志文件夹中生成的 LogsGenerated.log 文件已使用跟踪信息进行更新。

Along with that the file LogsGenerated.log that got generated within the log folder within the project was updated with the trace information.

selenium log4j logging 3

对于上面的两个案例,已经覆盖日志文件,但是,可以通过向 log4j2.properties 文件添加配置: appender.file.append=true 来将日志附加到日志文件。

In both the above cases, we had overwritten the log file, however, we can append logs to the log file by adding the configuration: appender.file.append=true to the log4j2.properties file.

此外,要禁用控制台和日志文件中的日志信息记录,则必须使用 logger.file.level = offrootLogger.level = off 更新 log4j2.properties。

Also, to disable logging information in the console and to the log file, we have to update the log4j2.properties with the logger.file.level = off and rootLogger.level = off.

指引教程:Selenium - Log4j 日志记录,本文到这里就结束了。我们从描述 Log4j 及其组件,设置 Log4j 的先决条件开始,最后通过说明如何将 Log4j 与 Selenium 结合使用,逐步讲解了创建 Log4j 的步骤。这让你全方位地了解了 Log4j。建议保持练习所学内容并探索其他与 Selenium 相关的内容,以加深理解并开阔视野。

This concludes our comprehensive take on the tutorial on Selenium - Log4j Logging. We’ve started with describing Log4j and its components, prerequisites to set up Log4j, and walked through steps to create Log4j with an example illustrating how to use it along with Selenium. This equips you with in-depth knowledge of the Log4j. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.