Logging API
Logging a notice
// Logs a notice
\Drupal::logger('my_module')->notice($message);
// Logs an error
\Drupal::logger('my_module')->error($message);
Severity Levels
php
<?php
use Drupal\Core\Logger\RfcLogLevel;
// Retrieve all severity levels:
$levels = RfcLogLevel::getLevels();
// Or get individual severity levels:
$severity = RfcLogLevel::EMERGENCY;
$severity = RfcLogLevel::ALERT;
$severity = RfcLogLevel::CRITICAL;
$severity = RfcLogLevel::ERROR;
$severity = RfcLogLevel::WARNING;
$severity = RfcLogLevel::NOTICE;
$severity = RfcLogLevel::INFO;
$severity = RfcLogLevel::DEBUG;
?>
Logging to Multiple Services
yaml
services:
myservice_that_needs_to_log_to_multiple_channels:
class: Drupal\mymodule\MyService
arguments: ['@logger.factory']
php
<?php
class MyService {
public function __construct($factory) {
$this->loggerFactory = $factory;
}
public function doStuff() {
// Logs a notice to "my_module" channel.
$this->loggerFactory->get('my_module')->notice($message);
// Logs an error to "my_other_module" channel.
$this->loggerFactory->get('my_other_module')->error($message);
}
}
Implementing a Custom Logger
yaml
services:
logger.mylog:
class: Drupal\mylog\Logger\MyLog
tags:
- { name: logger }
php
<?php
namespace Drupal\mylog\Logger;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;
class MyLog implements LoggerInterface {
use RfcLoggerTrait;
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array()) {
// Do stuff
}
}
?>
Shorthand functions
Instead of $logger->log($severity, $message, $context)
you can use these shorthand functions:
$logger->emergency($message, $context)
$logger->alert($message, $context)
$logger->critical($message, $context)
$logger->error($message, $context)
$logger->warning($message, $context)
$logger->notice($message, $context)
$logger->info($message, $context)
$logger->debug($message, $context)
Resources
Questions
What steps are required to implement a custom logger in Drupal?
To implement a custom logger in Drupal, define the service in services.yml
like this:
yaml
services:
logger.mylog:
class: Drupal\mylog\Logger\MyLog
tags:
- { name: logger }
Then create the logger class:
php
namespace Drupal\mylog\Logger;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;
class MyLog implements LoggerInterface {
use RfcLoggerTrait;
public function log($level, $message, array $context = []) {
// Custom logging logic here.
}
}
This integrates the custom logger with Drupal's logging system.
What is the purpose of the RfcLoggerTrait in Drupal's logging API?
The RfcLoggerTrait
provides a set of methods for logging messages with different severity levels. It extends the Psr\Log\LoggerTrait
to ensure compatibility with the PSR-3 logging standard.