<?php

namespace Drupal\{{ machine_name }}\Logger;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\Core\Logger\RfcLoggerTrait;
use Drupal\Core\Logger\RfcLogLevel;
use Psr\Log\LoggerInterface;

/**
 * Redirects messages to a file.
 */
class {{ class }} implements LoggerInterface {

  use RfcLoggerTrait;

  /**
   * A configuration object containing system.file settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The message's placeholders parser.
   *
   * @var \Drupal\Core\Logger\LogMessageParserInterface
   */
  protected $parser;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Constructs {{ class|article }} object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory object.
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
   *   The parser to use when extracting message variables.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser, DateFormatterInterface $date_formatter) {
    $this->config = $config_factory->get('system.file');
    $this->parser = $parser;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = []) {

    // Populate the message placeholders and then replace them in the message.
    $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
    $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);

    $entry = [
      'message' => strip_tags($message),
      'date' => $this->dateFormatter->format($context['timestamp']),
      'type' => $context['channel'],
      'ip' => $context['ip'],
      'request_uri' => $context['request_uri'],
      'referer' => $context['referer'],
      'severity' => (string) RfcLogLevel::getLevels()[$level],
      'uid' => $context['uid'],
    ];

    file_put_contents(
      $this->config->get('path.temporary') . '/drupal.log',
      print_r($entry, TRUE),
      FILE_APPEND
    );
  }

}
