5 * Contains \Drush\Log\DrushLog.
7 * This class is only used to convert logging calls made
8 * inside of Drupal into a logging format that is usable
9 * by Drush. This code is ONLY usable within the context
10 * of a bootstrapped Drupal 8 site.
12 * See Drush\Log\Logger for our actuall LoggerInterface
13 * implementation, that does the work of logging messages
14 * that originate from Drush.
19 use Drupal\Core\Logger\LogMessageParserInterface;
20 use Drupal\Core\Logger\RfcLoggerTrait;
21 use Drupal\Core\Logger\RfcLogLevel;
22 use Psr\Log\LoggerInterface;
25 * Redirects Drupal logging messages to Drush log.
27 * Note that Drupal extends the LoggerInterface, and
28 * needlessly replaces Psr\Log\LogLevels with Drupal\Core\Logger\RfcLogLevel.
29 * Doing this arguably violates the Psr\Log contract,
30 * but we can't help that here -- we just need to convert back.
32 class DrushLog implements LoggerInterface {
37 * The message's placeholders parser.
39 * @var \Drupal\Core\Logger\LogMessageParserInterface
44 * The logger that messages will be passed through to.
49 * Constructs a DrushLog object.
51 * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
52 * The parser to use when extracting message variables.
54 public function __construct(LogMessageParserInterface $parser, LoggerInterface $logger) {
55 $this->parser = $parser;
56 $this->logger = $logger;
62 public function log($level, $message, array $context = array()) {
63 // Translate the RFC logging levels into their Drush counterparts, more or
65 // @todo ALERT, CRITICAL and EMERGENCY are considered show-stopping errors,
66 // and they should cause Drush to exit or panic. Not sure how to handle this,
69 case RfcLogLevel::ALERT:
70 case RfcLogLevel::CRITICAL:
71 case RfcLogLevel::EMERGENCY:
72 case RfcLogLevel::ERROR:
73 $error_type = LogLevel::ERROR;
76 case RfcLogLevel::WARNING:
77 $error_type = LogLevel::WARNING;
80 // TODO: RfcLogLevel::DEBUG should be 'debug' rather than 'notice'?
81 case RfcLogLevel::DEBUG:
82 case RfcLogLevel::INFO:
83 case RfcLogLevel::NOTICE:
84 $error_type = LogLevel::NOTICE;
87 // TODO: Unknown log levels that are not defined
88 // in Psr\Log\LogLevel or Drush\Log\LogLevel SHOULD NOT be used. See
89 // https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
90 // We should convert these to 'notice'.
96 // Populate the message placeholders and then replace them in the message.
97 $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
99 // Filter out any placeholders that can not be cast to strings.
100 $message_placeholders = array_filter($message_placeholders, function ($element) {
101 return is_scalar($element) || is_callable([$element, '__toString']);
104 $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);
106 $this->logger->log($error_type, $message, $context);