Logging to Drupal’s watchdog systemfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

Effective logging is a crucial part of robust application development, and Drupal provides excellent facilities for logging through its watchdog system. The Watchdog, part of Drupal's logging API, helps you keep track of various events and errors within your site, aiding in debugging and monitoring the application's health. Today’s lesson will cover how to implement logging using the watchdog system in your Drupal modules, building upon the logging principles we've explored in previous lessons.

Understanding Drupal’s Watchdog System

Drupal's watchdog system is designed to record log messages about site activity, errors, and events into a centralized storage location. It is a core feature accessible via the watchdog function in Drupal 7 and the logger.factory in Drupal 8 and newer versions. With Watchdog, you can categorize logs, separate concerns into different channels, and specify log severity levels.

Key Features of the Watchdog System

  • Centralized Logging: All log messages are stored in a unified location for easy monitoring and analysis.
  • Severity Levels: Categorize logs by their importance, ranging from debug to critical levels.
  • Custom Channels: Use custom logging channels for different parts of your application or specific features.

Implementing Watchdog Logging in Your Module

We will demonstrate logging using Drupal’s watchdog system through the existing mymodule module to help you track relevant events effectively.

Step 1: Use Logger Factory for Watchdog Logging

In Drupal 8 and later, watchdog logging is achieved using the logger.factory service. The following example code demonstrates logging from a custom controller:



namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

class WatchdogLogController extends ControllerBase {

  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs a new WatchdogLogController object.
   *
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger service.
   */
  public function __construct(LoggerInterface $logger) {
    $this--->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory')->get('watchdog_channel')
    );
  }

  /**
   * Logs an example message to watchdog.
   */
  public function logExample() {
    // Log an informational message to the watchdog.
    $this->logger->info('This is an info log entry for {channel}.', ['channel' => 'watchdog_channel']);
    
    // Log an error message to the watchdog.
    $this->logger->error('An error occurred for {channel} instance.', ['channel' => 'watchdog_channel']);

    return [
      '#markup' => $this->t('Log entries added to the watchdog. Check the logs for details.'),
    ];
  }

}

Explanation:

In this setup, the logger.factory service is injected, targeting a custom channel named 'watchdog_channel'. This allows specific categorization under this channel, separating logs appropriately.

Step 2: Viewing Watchdog Logs

Access the stored log messages via the Drupal administrative interface:

  1. Navigate to Reports > Recent log messages (found at /admin/reports/dblog).
  2. Filter by time, severity, or channel (such as your custom 'watchdog_channel') to review specific log entries relevant to module operations.

Best Practices for Using Watchdog Logs

  • Appropriate Severity: Use different severity levels to accurately categorize the importance of log messages, ensuring critical errors receive prompt attention.
  • Clear Descriptions: Craft clear and structured log messages to simplify later reviews and analysis.
  • Sensitive Data Handling: Avoid logging sensitive information to maintain security and user privacy.

Extending Watchdog Functionality

While the default logging behavior writes logs to Drupal’s database, you can extend it with contributed modules like syslog, allowing logs to be stored in syslog files on your host system for more advanced logging facilities and integration with system-level monitoring tools.

Conclusion

Using Drupal’s watchdog system for logging is a powerful way to understand the inner workings of your application better and improve its robustness through effective monitoring. This lesson provided you with the tools to implement and manage logging within your module confidently.

As we continue this series, the next lesson will focus on logging to Drupal’s watchdog system in a more advanced context, exploring integration with system tools and extended functionalities. Join us as we delve deeper into comprehensive monitoring strategies for your Drupal applications!