Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active January 18, 2021 20:23
Show Gist options
  • Save JeffTomlinson/a1174cc268f20e606952755f504ed43e to your computer and use it in GitHub Desktop.
Save JeffTomlinson/a1174cc268f20e606952755f504ed43e to your computer and use it in GitHub Desktop.
Drupal 8 Logger Dependency Injection
services:
logger.channel.example_module:
parent: logger.channel_base
arguments: ['example_module']
<?php
namespace Drupal\example\Plugin\ExamplePlugin;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Logger\LoggerChannel;
/**
* Example plugin.
*/
class ExamplePlugin extends PluginBase implements ContainerFactoryPluginInterface {
/**
* LoggerChannel service.
*
* @var \Drupal\Core\Logger\LoggerChannel
*/
protected $logger;
/**
* ExamplePlugin constructor.
*
* @param array $configuration
* Configuration array.
* @param string $plugin_id
* The plugin id.
* @param string $plugin_definition
* The plugin definition.
* @param \Drupal\Core\Logger\LoggerChannel $logger
* Logger Channel service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerChannel $logger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->logger = $logger;
}
/**
* Creates an instance of the plugin.
*
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The container to pull out services used in the plugin.
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
*
* @return static
* Returns an instance of this plugin.
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('logger.channel.example_module')
);
}
/**
* {@inheritdoc}
*/
public function exampleMethod() {
if ($this->something()) {
$this->logger->notice('Something happened.');
}
else {
$this->logger->error('Nothing happened.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment