Using logger in drupal

PHOTO EMBED

Fri Jan 14 2022 11:26:54 GMT+0000 (UTC)

Saved by @igor #drupal #php

// If we want to use it as a dependency injection (we should),
// than this is the right way.

/**
 * Logger interface.
 *
 * @var \Psr\Log\LoggerInterface
 */
protected $logger;

// After that we add it to constructor method.

/**
* Controller_name constructor
 *
 * @param \Psr\Log\LoggerInterface $logger
 *  Logger interface.
 */
public function __construct(LoggerInterface $logger) {
  $this->logger = $logger;
}

public function someFunction(){
  if (something) {
    // Line of code...
  } else {
    $this->logger->error('Error message');
  }
}
content_copyCOPY