Using logger.factory for module logsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

In the process of developing robust modules in Drupal, keeping track of events and errors through logging is essential. Effective logging not only aids in debugging but also provides valuable insights into the behavior of your application. Drupal offers an efficient logging mechanism through the logger.factory service. In this lesson, we'll explore how to use this service to implement reliable logging within your custom Drupal modules.

Understanding logger.factory

Drupal’s logging system is supported by the logger.factory service, which provides a straightforward method to log messages across different channels. By default, Drupal logs entries in a database table, which can be viewed in the administrative interface, but you can also configure other destinations such as syslog or watchdog.

Benefits of Using logger.factory

  • Centralized logging to capture all informational and error messages in one place.
  • Improves application monitoring by making it easier to track unexpected behavior.
  • Supports various log levels, such as alert, critical, debug, emergency, error, info, notice, and warning.

Implementing logger.factory in Your Module

We will demonstrate using logger.factory within a custom module, continuing with our existing module mymodule.

Step 1: Inject the Logger Service

To use the logger service, inject it into your service or controller. Here is an example of injecting it into a controller:



namespace Drupal\mymodule\Controller;

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

class LogExampleController extends ControllerBase {
  
  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs a new LogExampleController 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('mymodule')
    );
  }

  /**
   * Log example messages.
   */
  public function logMessages() {
    $this->logger->info('An example info log entry from @module.', ['@module' => 'mymodule']);
    $this->logger->error('An example error log entry from @module.', ['@module' => 'mymodule']);
    
    return [
      '#markup' => $this->t('Log entries have been recorded. Check the logs for details.'),
    ];
  }

}

Explanation:

This code demonstrates dependency injection of the logger service into a controller. The create() method is used to specify mymodule as the logging channel, allowing you to differentiate log entries by module or feature area. The logMessages() function illustrates logging at different levels, recording both informational and error messages.

Step 2: Log Different Levels of Messages

Logging levels help categorize messages based on severity. Here is how you might use different log levels:

  • debug: Use for detailed debugging information.
  • info: General information for logging normal operations.
  • notice: Log normal but significant events.
  • warning: Indications of potential problems.
  • error: Log runtime errors that do not require immediate action.
  • critical, alert, emergency: High priority log levels for severe issues.

Viewing and Managing Logs

Drupal logs are easily accessible from the administrative interface:

  1. Navigate to Reports > Recent log messages (at /admin/reports/dblog).
  2. There, you can filter logs by severity level, channel (i.e., mymodule), or time to quickly identify issues or events.

Best Practices for Logging

  • Consistent Message Structure: Use a consistent message format, including placeholders for dynamic data, for easier log analysis.
  • Avoid Sensitive Information: Never log sensitive user data such as passwords or personal details.
  • Use Appropriate Log Levels: Match log levels to the severity of the event to avoid log flooding and improve the signal-to-noise ratio.

Conclusion

In this lesson, we explored how to effectively use the logger.factory service in Drupal to manage and maintain insightful logs for your modules. This approach not only aids in debugging but also provides actionable insights into your application’s behavior over time.

As we continue this series, the next lesson will guide you through defining a custom logger channel, offering even more flexibility in organizing your logs and enhancing your site's monitoring capabilities. Stay tuned as we delve deeper into Drupal's powerful logging system!