DEV Community

Cover image for πŸ“ A Complete Guide to Setting up Logging in WebdriverIO Frameworks 🎯
Hardik Chotaliya
Hardik Chotaliya

Posted on • Edited on • Originally published at hardikchotaliya.hashnode.dev

πŸ“ A Complete Guide to Setting up Logging in WebdriverIO Frameworks 🎯

Optimizing Test Automation with Winston Logger in WebdriverIO


πŸ–ŠοΈ Introduction

Logging is an essential aspect of any automation framework. It not only helps us monitor the progress of test execution but also plays a crucial role in debugging issues. In this blog post, we will explore how to set up a logger for a WebdriverIO automation framework using TypeScript. We will use the popular Winston logger to enhance our test reporting and debugging capabilities.


πŸ” Why Logging Matters

Before diving into the details of setting up a logger in a WebdriverIO framework, let's understand why logging is crucial:

  1. Monitoring Test Progress: Logging allows us to keep track of each step of our test cases, making it easier to identify the progress and identify any issues during test execution.

  2. Debugging: When a test fails, logs can be a lifesaver. They provide valuable information that helps us diagnose and fix problems quickly. Without logs, identifying the root cause of a failure can be a time-consuming task.

  3. Reporting: Comprehensive logs are valuable for generating detailed test reports. They can be used to create meaningful reports that stakeholders can use to understand the test results.


βš™οΈ Setting Up Winston Logger

Winston is a versatile and widely used logger in the Node.js ecosystem. In the context of a WebdriverIO framework, we'll use it for console logging. Here are the steps to set up the Winston logger:

Step 1: Installation

First, you need to install the Winston package as a development dependency. You can do this using npm:

install --save-dev winston
Enter fullscreen mode Exit fullscreen mode

Step 2: Configuration

Next, create a logger.ts file in your framework project. In this file, you'll define the logger and its configuration. Here's a simple example of what it might look like:

import winston from "winston";

// Define a function to format console messages
const consoleFormat = winston.format.printf(({ level, message, timestamp }) => {
    // Colorize and uppercase the log level
    const logLevel = winston.format.colorize().colorize(level, `${level.toUpperCase()}`);
    // Format the log message with timestamp and log level
    return `${timestamp} [${logLevel}]: ${message}`;
});

/**
 * Create a Winston logger with a Console transport.
 * @type {winston.Logger}
 */
const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({
            // Set log level from the environment variable
            level: process.env.LOG_LEVEL,
            handleExceptions: true,
            format: winston.format.combine(
                winston.format.timestamp(), // Add timestamp to log entries
                consoleFormat // Apply the custom console log format
            )
        })
    ]
});

// Log any unknown errors from the logger
logger.on("error", error => {
    console.log("Unknown error in Winston logger");
    console.log(error.message);
});

export default logger;
Enter fullscreen mode Exit fullscreen mode

In this example, we set up a basic logger that logs messages in a colored format to the console.

πŸ‘©πŸΌβ€πŸ« Explanation:

  1. Import the required winston library for logging.

  2. Create a function consoleFormat that formats log messages. It takes the log level, message, and timestamp as input and colorizes the log level. The formatted message includes the timestamp, log level (in uppercase), and the actual log message.

  3. Create a Winston logger by using winston.createLogger. It uses a Console transport for logging.

  4. Inside the logger configuration, set the log level based on the LOG_LEVEL environment variable. This allows you to control the log level dynamically.

  5. Add the handleExceptions: true option to handle exceptions and log them.

  6. Apply the custom format to the log entries, including adding a timestamp and using the consoleFormat function for formatting.

  7. Create an event listener for the "error" event on the logger. This will catch and log any unknown errors that may occur within the logger.

  8. Export the configured logger for use in other parts of your application.

This code sets up a flexible Winston logger with customizable log levels, proper formatting, and the ability to catch and log errors. It is well-documented for clarity and maintain

Step 3: Using the Logger

Now, you can use the logger in your test scripts. Import it and utilize its various methods to log messages according to their significance. For example:

import logger from './path-to-logger/logger';

// Log an informational message
logger.info('Starting the test...');

// Log an error message
logger.error('An error occurred.');

// Log a debugging message
logger.debug('Debug information...');
Enter fullscreen mode Exit fullscreen mode

Step 4: Configuring Log Levels

You can configure log levels based on the environment to make your logger more versatile. For instance, you might want to log more information during debugging but limit logging during regular test runs. You can set the log level using an environment variable like process.env.loglevel.


πŸƒβ€β™€οΈ Running Your Tests with Logging

With the Winston logger integrated into your WebdriverIO framework, you'll see detailed log messages as your tests run. These logs will include information about the progress of your tests and any errors encountered.


🏁 Conclusion

In this blog post, we've learned the importance of logging in a WebdriverIO + TypeScript framework and how to set up a powerful logger using Winston. Effective logging is crucial for monitoring test progress, debugging, and generating meaningful reports. By implementing logging in your automation framework, you can improve the efficiency and reliability of your test suite, making it easier to identify and address issues as they arise. Happy testing!

If you have any questions or need further assistance with setting up a logger in your automation framework, feel free to reach out to the below GitHub Repository!

WebdriverIO-TS-Cucumber-e2e [WebdriverIO Version - 8.18.2]


πŸ–₯️ System Requirements

You’ll need Node.js installed.

  • Install at least v16.x or higher as this is the oldest active LTS version
  • Only releases that are or will become an LTS release are officially supported ( If Node is not currently installed on your system, we suggest utilizing a tool such as NVM or Volta to assist in managing multiple active Node.js versions. NVM is a popular choice, while Volta is also a good alternative. )

πŸƒ To run your tests, execute:

$ cd /Users/yserName/Documents/workspace/WebdriverIO-TS-Cucumber-e2e

$ npm run wdio

The wdio-local script is used to run the WebdriverIO tests, generate an Allure report, and open the Allure report in a web browser.

$ npm run wdio-local

πŸ“¦ Package dependencies Usage:

  • @wdio/allure-reporter - This dependency is used to generate Allure reports from WebdriverIO tests.
  • @wdio/cli: This dependency is used to run WebdriverIO tests.
  • @wdio/cucumber-framework: This dependency is…





tags: WebDriverIO,Logging,WebdriverIOFrameworks,LoggingGuide,WebAutomation,TestAutomation,Selenium,FrontendTesting,AutomationTesting,LoggingConfiguration,LoggingBestPractices


Top comments (0)