You can now autoconfigure any service class that implements \Psr\Log\LoggerAwareInterface to be setter-injected with a logger defined in the same module with a service name following the pattern: 'logger.channel.<MODULE_NAME>'.
This means you no longer need to explicitly define a logger in your service class constructor.
For example:
example.services.yml:
services:
_defaults:
# autoconfigure must be on
autoconfigure: true
my_module.my_service:
class: Drupal\my_module\MyService
# The ID after `logger.channel.` must the the same machine name as the module.
logger.channel.my_module:
parent: logger.channel_base
arguments: ['my_module']
Before
Explicitly requiring a logger in the constructor.
use \Psr\Log\LoggerInterface;
class LoggerAwareExample {
protected LoggerInterface $logger;
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
}
After
Container autoconfiguration sets the $logger class property provided by the trait via
use \Psr\Log\LoggerAwareInterface;
use \Psr\Log\LoggerAwareTrait;
class LoggerAwareExample implements LoggerAwareInterface {
use LoggerAwareTrait;
public function myMethod(): {
$this->logger->debug(...); // Use the logger as normal
}
}
In the above example the 'logger.channel.my_module' service will automatically be set on a $logger property in theLoggerAwareExample instance via \Psr\Log\LoggerAwareTrait::setLogger.
To make use of this feature, services must:
- Implement
\Psr\Log\LoggerAwareInterface - Import the
\Psr\Log\LoggerAwareTraittrait. - Utilize autoconfiguration for services.
- Have an existing logger.channel.my_module logger service.