LoggerChannelTrait.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Drupal\Core\Logger;
  3. /**
  4. * Wrapper methods for the logger factory service.
  5. *
  6. * This utility trait should only be used in application-level code, such as
  7. * classes that would implement ContainerInjectionInterface. Services registered
  8. * in the Container should not use this trait but inject the appropriate service
  9. * directly for easier testing.
  10. *
  11. * @see \Drupal\Core\DependencyInjection\ContainerInjectionInterface
  12. */
  13. trait LoggerChannelTrait {
  14. /**
  15. * The logger channel factory service.
  16. *
  17. * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
  18. */
  19. protected $loggerFactory;
  20. /**
  21. * Gets the logger for a specific channel.
  22. *
  23. * @param string $channel
  24. * The name of the channel. Can be any string, but the general practice is
  25. * to use the name of the subsystem calling this.
  26. *
  27. * @return \Psr\Log\LoggerInterface
  28. * The logger for the given channel.
  29. *
  30. * @todo Require the use of injected services:
  31. * https://www.drupal.org/node/2733703
  32. */
  33. protected function getLogger($channel) {
  34. if (!$this->loggerFactory) {
  35. $this->loggerFactory = \Drupal::service('logger.factory');
  36. }
  37. return $this->loggerFactory->get($channel);
  38. }
  39. /**
  40. * Injects the logger channel factory.
  41. *
  42. * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
  43. * The logger channel factory service.
  44. *
  45. * @return $this
  46. */
  47. public function setLoggerFactory(LoggerChannelFactoryInterface $logger_factory) {
  48. $this->loggerFactory = $logger_factory;
  49. return $this;
  50. }
  51. }