Last active
December 22, 2021 07:49
-
-
Save JeffTomlinson/72563f86d5363de2bc0fec3f6b2af8ac to your computer and use it in GitHub Desktop.
Drupal 8 Logger Dependency Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Log something. | |
*/ | |
function log_something() { | |
/Drupal::service('my_module.my_service')->logSomething('Word to the mutha'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
my_module.my_service: | |
class: Drupal\my_module\Services\MyService | |
arguments: | |
- '@logger.factory' | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this.
One correction: Should use
LoggerChannelFactoryInterface
instead ofLoggerChannelFactory
. I got an error when trying to useLoggerChannelFactory
. More info in this drupal.org issue.