0
0
Selenium Javatesting~8 mins

Logging with Log4j in Selenium Java - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Logging with Log4j
Folder Structure
src/
├── main/
│   ├── java/
│   │   └── com/example/project/
│   │       └── utils/
│   │           └── LoggerUtil.java  <-- Central logging utility
│   └── resources/
│       └── log4j2.xml               <-- Log4j configuration file
└── test/
    ├── java/
    │   └── com/example/project/tests/
    │       └── SampleTest.java      <-- Selenium test using Logger
    └── resources/
        └── testdata.properties      <-- Test data and configs
Test Framework Layers
  • Logger Utility Layer: Contains LoggerUtil.java which wraps Log4j2 logger setup and usage.
  • Test Layer: Selenium test classes that call LoggerUtil to log test steps and results.
  • Configuration Layer: log4j2.xml defines logging levels, appenders (console, file), and formats.
  • Utilities Layer: Helper classes for common functions, including logging helper.
  • Resources Layer: Holds configuration files like log4j2.xml and test data properties.
Configuration Patterns
  • log4j2.xml: Central XML file to configure logging levels (INFO, DEBUG, ERROR), appenders (console, file), and patterns.
  • Environment-based Logging: Use different log4j2.xml files or properties to adjust logging verbosity per environment (dev, test, prod).
  • Dynamic Log Level: Configure log level via system properties or environment variables to avoid code changes.
  • Logger Initialization: LoggerUtil initializes Log4j logger once per class using LogManager.getLogger(ClassName.class).
Test Reporting and CI/CD Integration
  • Logs generated by Log4j are saved to files and console for easy debugging.
  • Log files can be archived and attached to CI/CD pipeline reports (e.g., Jenkins, GitHub Actions).
  • Use log levels to filter important messages in CI logs to reduce noise.
  • Integrate with test reports (e.g., Allure, TestNG reports) by linking log files or embedding key logs.
  • Automate log cleanup and rotation to manage disk space in CI environments.
Best Practices
  • Use Logger per Class: Create a logger instance per class to identify log source easily.
  • Log Meaningful Messages: Include context like test step, input data, and expected vs actual results.
  • Use Appropriate Log Levels: DEBUG for detailed info, INFO for general steps, ERROR for failures.
  • Externalize Configuration: Keep log4j2.xml outside code to change logging without recompiling.
  • Avoid Logging Sensitive Data: Do not log passwords or personal info to protect privacy.
Self Check

Where in this folder structure would you add a new logger utility class to support logging test execution details?

Key Result
Centralize logging with Log4j2 using a dedicated utility class and external XML configuration for flexible, meaningful test logs.