0
0
Selenium Javatesting~15 mins

Logging with Log4j in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify logging messages are generated during login test using Log4j
Preconditions (3)
Step 1: Open the browser and navigate to the login page URL
Step 2: Log info message: 'Navigated to login page'
Step 3: Enter 'admin@test.com' in the email input field with id 'email'
Step 4: Log debug message: 'Entered email address'
Step 5: Enter 'Pass123!' in the password input field with id 'password'
Step 6: Log debug message: 'Entered password'
Step 7: Click the login button with id 'loginBtn'
Step 8: Log info message: 'Clicked login button'
Step 9: Wait until the URL changes to the dashboard URL 'https://example.com/dashboard'
Step 10: Log info message: 'Login successful, dashboard loaded'
✅ Expected Result: The login process completes successfully and the log file contains the info and debug messages in the correct order.
Automation Requirements - Selenium WebDriver with TestNG and Log4j2
Assertions Needed:
Verify the current URL is 'https://example.com/dashboard' after login
Verify log messages are generated (info and debug) during the test execution
Best Practices:
Use explicit waits to wait for page load or URL change
Use Page Object Model to separate page actions
Use Log4j2 logger instance properly with correct log levels
Avoid Thread.sleep; use WebDriverWait
Keep locators stable and readable (use By.id)
Automated Solution
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.time.Duration;

public class LoginTest {

    private WebDriver driver;
    private WebDriverWait wait;
    private static final Logger logger = LogManager.getLogger(LoginTest.class);

    @BeforeClass
    public void setUp() {
        // Setup ChromeDriver path if needed
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        logger.info("Browser launched");
    }

    @Test
    public void testLoginWithLogging() {
        driver.get("https://example.com/login");
        logger.info("Navigated to login page");

        driver.findElement(By.id("email")).sendKeys("admin@test.com");
        logger.debug("Entered email address");

        driver.findElement(By.id("password")).sendKeys("Pass123!");
        logger.debug("Entered password");

        driver.findElement(By.id("loginBtn")).click();
        logger.info("Clicked login button");

        // Wait until URL changes to dashboard
        wait.until(ExpectedConditions.urlToBe("https://example.com/dashboard"));
        logger.info("Login successful, dashboard loaded");

        Assert.assertEquals(driver.getCurrentUrl(), "https://example.com/dashboard", "Dashboard URL should be loaded after login");
    }

    @AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
            logger.info("Browser closed");
        }
    }
}

This test class uses Selenium WebDriver with TestNG and Log4j2 for logging.

1. Logger setup: We create a static logger instance using LogManager.getLogger for this class.

2. Setup method: Launches Chrome browser and initializes explicit wait. Logs info message.

3. Test method: Navigates to login page and logs info. Enters email and password with debug logs after each input. Clicks login button and logs info. Waits explicitly for the dashboard URL to load and logs success info. Asserts the URL is correct.

4. Teardown method: Closes browser and logs info.

Explicit waits avoid flaky tests. Using By.id locators keeps selectors stable. Logging at info and debug levels helps track test flow and data entry.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits
{'mistake': 'Not initializing or configuring Log4j properly', 'why_bad': "Without proper Log4j setup, logs won't be generated or saved, making debugging difficult.", 'correct_approach': 'Include a valid log4j2.xml configuration file in the resources and initialize logger with LogManager.getLogger.'}
Using hardcoded XPath locators instead of stable By.id
Logging sensitive information like passwords
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials (valid and invalid) using TestNG data provider.

Show Hint