How to Set Up Log4j2 Logging with LogUtils in AutomationFrameworkSelenium
To configure logging in the anhtester/automationframeworkselenium project, add the Log4j2 dependencies to your Maven pom.xml, place the log4j2.properties configuration file in src/main/resources, and use the static methods provided by com.anhtester.utils.LogUtils throughout your test classes.
The AutomationFrameworkSelenium repository implements a centralized logging strategy using Log4j2 (version 2.25.2) wrapped behind a utility class. This design allows test engineers to emit structured logs to both console and rolling files without instantiating loggers in every class. The setup requires three specific components working together: the Maven build configuration, the Log4j2 properties file, and the LogUtils wrapper.
Add Log4j2 Dependencies to pom.xml
The project declares Log4j2 dependencies in the main pom.xml file located at the repository root. These entries ensure the Log4j2 API and core libraries are available on the classpath at runtime.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.25.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.25.2</version>
</dependency>
According to the source code in pom.xml, these dependencies enable the framework to utilize Log4j2's advanced features including asynchronous logging and custom appenders. No additional SLF4J bridges are required for the basic setup described here.
Configure Log4j2 with log4j2.properties
Place the configuration file at src/main/resources/log4j2.properties to ensure it is packaged into the classpath during test execution. This file defines two appenders: a console appender for immediate feedback and a rolling file appender for persistent storage.
Key configuration details from src/main/resources/log4j2.properties:
- Console Appender (
StdoutAppender): Outputs logs to standard out with a pattern showing the level, timestamp (dd-MM-yyyy HH:mm:ss), logger name, and message - Rolling File Appender (
RollingAppender): Writes toexports/logs/applog.logwith daily time-based rotation and size-based triggers (10 MB max), retaining up to 20 archived files - Root Logger Level: Set to
infoby default, capturing INFO, WARN, ERROR, and FATAL levels
status=info
name=Log4j2PropertiesConfig
appenders=a_console, a_rolling
rootLogger.level=info
rootLogger.appenderRefs=ar_console,ar_rolling
rootLogger.appenderRef.ar_console.ref=StdoutAppender
rootLogger.appenderRef.ar_rolling.ref=RollingAppender
# Console appender
appender.a_console.type=Console
appender.a_console.name=StdoutAppender
appender.a_console.layout.type=PatternLayout
appender.a_console.layout.pattern=[%level] %d{dd-MM-yyyy HH:mm:ss} [%c{1}] - %msg%n
# Rolling file appender
appender.a_rolling.type=RollingFile
appender.a_rolling.name=RollingAppender
appender.a_rolling.fileName=exports/logs/applog.log
appender.a_rolling.filePattern=exports/logs/applog-%d{dd-MM-yyyy}.log
appender.a_rolling.layout.type=PatternLayout
appender.a_rolling.layout.pattern=[%level] %d{dd-MM-yyyy HH:mm:ss} [%t] [%c{1}] - %msg%n
appender.a_rolling.policies.type=Policies
appender.a_rolling.policies.time.type=TimeBasedTriggeringPolicy
appender.a_rolling.policies.time.interval=1
appender.a_rolling.policies.time.modulate=true
appender.a_rolling.policies.size.type=SizeBasedTriggeringPolicy
appender.a_rolling.policies.size.size=10MB
appender.a_rolling.strategy.type=DefaultRolloverStrategy
appender.a_rolling.strategy.max=20
The rolling policy ensures that log files do not consume excessive disk space during long test suite executions.
Use the LogUtils Wrapper Class
The LogUtils class at src/main/java/com/anhtester/utils/LogUtils.java provides a single point of access for all logging operations. It initializes a static Logger instance via LogManager.getLogger(LogUtils.class) and exposes static convenience methods that forward calls to Log4j2.
Available static methods in LogUtils:
info(String message)– General information messageswarn(String message)– Warning conditionserror(String message)– Error eventserror(String message, Throwable throwable)– Error events with stack tracesdebug(String message)– Detailed debugging informationfatal(String message)– Severe error events
Because LogUtils abstracts the underlying Log4j2 implementation, calling code remains decoupled from the specific logging framework. This abstraction allows the framework maintainers to swap logging implementations in the future without modifying hundreds of test classes.
Practical Usage Examples
Import LogUtils in your test classes and invoke the static methods directly. The following example from the framework's usage patterns demonstrates typical logging in a TestNG test method:
package com.anhtester.tests;
import com.anhtester.utils.LogUtils;
import org.testng.annotations.Test;
public class SampleTest {
@Test
public void loginTest() {
LogUtils.info("Starting login test");
try {
// Test execution steps here
LogUtils.info("Navigating to login page");
LogUtils.info("Entering credentials");
LogUtils.pass("Login succeeded");
} catch (Exception e) {
LogUtils.error("Login failed", e);
}
LogUtils.info("Login test finished");
}
}
Throughout the framework, classes like ZipUtils, ObjectUtils, and ExtentReportManager utilize this same pattern, ensuring consistent log formatting and destination handling across the entire codebase.
Adding Custom Log Levels
If you require additional log levels (such as TRACE), modify src/main/java/com/anhtester/utils/LogUtils.java to expose the new level:
public static void trace(String message) {
LOGGER.trace(message);
}
After adding this method, call LogUtils.trace("Detailed diagnostic message") anywhere in your test code. This modification centralizes the change in one location rather than requiring updates across multiple test files.
Summary
- Dependencies: Log4j2 version 2.25.2 is declared in
pom.xmlwithlog4j-apiandlog4j-coreartifacts - Configuration: The
log4j2.propertiesfile insrc/main/resourcesconfigures console output and rolling file storage toexports/logs/applog.log - Implementation:
LogUtils.javaprovides static wrapper methods (info(),warn(),error(),debug(),fatal()) that delegate to Log4j2 - Usage: Import
com.anhtester.utils.LogUtilsand call static methods directly in test classes for consistent, configurable logging - Maintenance: As a single-point wrapper,
LogUtilsallows framework-wide logging changes without modifying individual test classes
Frequently Asked Questions
Where is the Log4j2 configuration file located in the project?
The configuration file is located at src/main/resources/log4j2.properties. This location ensures that Maven packages the file into the classpath during the build process, allowing Log4j2 to automatically detect and load the configuration at runtime.
How do I change the default log level from INFO to DEBUG?
Open src/main/resources/log4j2.properties and modify the line rootLogger.level=info to rootLogger.level=debug. You can also adjust individual appender thresholds by adding specific logger configurations for package names if you need granular control over specific framework components.
Where are the physical log files stored when tests execute?
According to the log4j2.properties configuration, rolling log files are stored in the exports/logs/ directory relative to the project root. The active log file is named applog.log, while archived files follow the pattern applog-dd-MM-yyyy.log with a retention policy of 20 files maximum.
Can I use LogUtils in custom utility classes outside of test classes?
Yes, LogUtils is designed as a global utility class. Any Java class in the project can import com.anhtester.utils.LogUtils and invoke its static methods. The class is commonly used throughout the framework in utilities like ZipUtils and ExtentReportManager, not just in TestNG test classes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →