Skip to content
This repository has been archived by the owner on Dec 1, 2021. It is now read-only.

Latest commit

 

History

History
103 lines (84 loc) · 2.24 KB

4.4-essential-apis-logging.md

File metadata and controls

103 lines (84 loc) · 2.24 KB

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
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

services:
  myservice_that_needs_to_log_to_multiple_channels:
    class: Drupal\mymodule\MyService
    arguments: ['@logger.factory']
<?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

services:
  logger.mylog:
    class: Drupal\mylog\Logger\MyLog
    tags:
      - { name: logger }
<?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)

Additional Resources