Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / vendor / chi-teck / drupal-code-generator / templates / d8 / service / logger.twig
1 <?php
2
3 namespace Drupal\{{ machine_name }}\Logger;
4
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\Datetime\DateFormatterInterface;
7 use Drupal\Core\Logger\LogMessageParserInterface;
8 use Drupal\Core\Logger\RfcLoggerTrait;
9 use Drupal\Core\Logger\RfcLogLevel;
10 use Psr\Log\LoggerInterface;
11
12 /**
13  * Redirects logging messages to a file.
14  */
15 class {{ class }} implements LoggerInterface {
16
17   use RfcLoggerTrait;
18
19   /**
20    * A configuration object containing system.file settings.
21    *
22    * @var \Drupal\Core\Config\Config
23    */
24   protected $config;
25
26   /**
27    * The message's placeholders parser.
28    *
29    * @var \Drupal\Core\Logger\LogMessageParserInterface
30    */
31   protected $parser;
32
33   /**
34    * The date formatter service.
35    *
36    * @var \Drupal\Core\Datetime\DateFormatterInterface
37    */
38   protected $dateFormatter;
39
40   /**
41    * Constructs a SysLog object.
42    *
43    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
44    *   The configuration factory object.
45    * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
46    *   The parser to use when extracting message variables.
47    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
48    *   The date formatter service.
49    */
50   public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser, DateFormatterInterface $date_formatter) {
51     $this->config = $config_factory->get('system.file');
52     $this->parser = $parser;
53     $this->dateFormatter = $date_formatter;
54   }
55
56   /**
57    * {@inheritdoc}
58    */
59   public function log($level, $message, array $context = []) {
60
61     // Populate the message placeholders and then replace them in the message.
62     $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
63     $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);
64
65     $entry = [
66       'message' => strip_tags($message),
67       'date' => $this->dateFormatter->format($context['timestamp']),
68       'type' => $context['channel'],
69       'ip' => $context['ip'],
70       'request_uri' => $context['request_uri'],
71       'referer' => $context['referer'],
72       'severity' => (string) RfcLogLevel::getLevels()[$level],
73       'uid' => $context['uid'],
74     ];
75
76     file_put_contents(
77       $this->config->get('path.temporary') . '/drupal.log',
78       print_r($entry, TRUE),
79       FILE_APPEND
80     );
81   }
82
83 }