How to create a custom logger channel in Drupal

Logging is convenient for storing information about important events in the application. You could use it to find out if any errors occurred, debug issues, and any other important information.

A lot happens in Drupal, and it is hard to find relevant information, so it is appropriate to categorize log messages based on functionality.

Below are two files - the first shows how to create the channel, and you can do it inside your module's services file. Channel naming could use your module name or service/functionality name. The second file shows how to use it inside your service class.

File: my_module/my_module.services.yml
services: my_module.my_service: class: \Drupal\my_module\MyService arguments: ['@logger.my_module'] logger.my_module: parent: logger.channel_base arguments: ['my_module']
File: my_module/src/MyService.php
<?php namespace Drupal\my_service; use Drupal\Core\Logger\LoggerChannelInterface; /** * MyService class. */ class MyService { /** * Logger channel. * * @var \Drupal\Core\Logger\LoggerChannelInterface */ protected LoggerChannelInterface $logger; /** * Constructor. * * @param \Drupal\Core\Logger\LoggerChannelInterface $logger * Logger channel. */ public function __construct(LoggerChannelInterface $logger) { $this->logger = $logger; // Example call. $this->logger->info('Info from MyService.'); } }
Buy Me a Coffee at ko-fi.com

Add new comment