1<?php
2
3/**
4 * @see       https://github.com/laminas/laminas-log for the canonical source repository
5 * @copyright https://github.com/laminas/laminas-log/blob/master/COPYRIGHT.md
6 * @license   https://github.com/laminas/laminas-log/blob/master/LICENSE.md New BSD License
7 */
8
9namespace Laminas\Log\Writer;
10
11use Laminas\Log\Exception;
12use Laminas\Log\Logger;
13use Psr\Log\LoggerAwareTrait as PsrLoggerAwareTrait;
14use Psr\Log\LoggerInterface as PsrLoggerInterface;
15use Psr\Log\LogLevel;
16use Psr\Log\NullLogger;
17use Traversable;
18
19/**
20 * Proxies log messages to an existing PSR-3 compliant logger.
21 */
22class Psr extends AbstractWriter
23{
24    use PsrLoggerAwareTrait;
25
26    /**
27     * Map priority to PSR-3 LogLevels
28     *
29     * @var int[]
30     */
31    protected $psrPriorityMap = [
32        Logger::EMERG  => LogLevel::EMERGENCY,
33        Logger::ALERT  => LogLevel::ALERT,
34        Logger::CRIT   => LogLevel::CRITICAL,
35        Logger::ERR    => LogLevel::ERROR,
36        Logger::WARN   => LogLevel::WARNING,
37        Logger::NOTICE => LogLevel::NOTICE,
38        Logger::INFO   => LogLevel::INFO,
39        Logger::DEBUG  => LogLevel::DEBUG,
40    ];
41
42    /**
43     * Default log level (warning)
44     *
45     * @var int
46     */
47    protected $defaultLogLevel = LogLevel::WARNING;
48
49    /**
50     * Constructor
51     *
52     * Set options for a writer. Accepted options are:
53     *
54     * - filters: array of filters to add to this filter
55     * - formatter: formatter for this writer
56     * - logger: PsrLoggerInterface implementation
57     *
58     * @param  array|Traversable|PsrLoggerInterface $options
59     * @throws Exception\InvalidArgumentException
60     */
61    public function __construct($options = null)
62    {
63        if ($options instanceof PsrLoggerInterface) {
64            $this->setLogger($options);
65        }
66
67        if ($options instanceof Traversable) {
68            $options = iterator_to_array($options);
69        }
70
71        if (is_array($options) && isset($options['logger'])) {
72            $this->setLogger($options['logger']);
73        }
74
75        parent::__construct($options);
76
77        if (null === $this->logger) {
78            $this->setLogger(new NullLogger);
79        }
80    }
81
82    /**
83     * Write a message to the PSR-3 compliant logger.
84     *
85     * @param array $event event data
86     * @return void
87     */
88    protected function doWrite(array $event)
89    {
90        $priority = $event['priority'];
91        $message  = $event['message'];
92        $context  = $event['extra'];
93
94        $level = isset($this->psrPriorityMap[$priority])
95            ? $this->psrPriorityMap[$priority]
96            : $this->defaultLogLevel;
97
98        $this->logger->log($level, $message, $context);
99    }
100}
101