Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active December 22, 2021 07:49
Show Gist options
  • Save JeffTomlinson/72563f86d5363de2bc0fec3f6b2af8ac to your computer and use it in GitHub Desktop.
Save JeffTomlinson/72563f86d5363de2bc0fec3f6b2af8ac to your computer and use it in GitHub Desktop.
Drupal 8 Logger Dependency Injection
<?php
/**
* Log something.
*/
function log_something() {
/Drupal::service('my_module.my_service')->logSomething('Word to the mutha');
}
services:
my_module.my_service:
class: Drupal\my_module\Services\MyService
arguments:
- '@logger.factory'
<?php
namespace Drupal\my_module\Services;
use Drupal\Core\Logger\LoggerChannelFactory;
/**
* Class MyService.
*
* @package Drupal\my_module\Services
*/
class MyService {
/**
* Logger Factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactory
*/
protected $loggerFactory;
/**
* Constructor.
*/
public function __construct(LoggerChannelFactory $loggerFactory) {
$this->loggerFactory = $loggerFactory->get('my_module');
}
public function logSomething($something) {
$this->loggerFactory->error('Yo: @something', [
'@something' => $something,
]);
}
}
@juhog
Copy link

juhog commented Nov 6, 2017

Thanks for this.

One correction: Should use LoggerChannelFactoryInterface instead of LoggerChannelFactory. I got an error when trying to use LoggerChannelFactory. More info in this drupal.org issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment