1<?php
2
3namespace Elastica;
4
5use Psr\Log\AbstractLogger;
6
7/**
8 * Elastica log object.
9 *
10 * @author Nicolas Ruflin <spam@ruflin.com>
11 */
12class Log extends AbstractLogger
13{
14    /**
15     * Log path or true if enabled.
16     *
17     * @var string|bool
18     */
19    protected $_log;
20
21    /**
22     * Last logged message.
23     *
24     * @var string Last logged message
25     */
26    protected $_lastMessage;
27
28    /**
29     * Inits log object.
30     *
31     * @param string|bool String to set a specific file for logging
32     */
33    public function __construct($log = '')
34    {
35        $this->setLog($log);
36    }
37
38    /**
39     * Log a message.
40     *
41     * @param mixed  $level
42     * @param string $message
43     * @param array  $context
44     *
45     * @return void|null
46     */
47    public function log($level, $message, array $context = [])
48    {
49        $context['error_message'] = $message;
50        $this->_lastMessage = JSON::stringify($context);
51
52        if (!empty($this->_log) && \is_string($this->_log)) {
53            \error_log($this->_lastMessage.PHP_EOL, 3, $this->_log);
54        } else {
55            \error_log($this->_lastMessage);
56        }
57    }
58
59    /**
60     * Enable/disable log or set log path.
61     *
62     * @param bool|string $log Enables log or sets log path
63     *
64     * @return $this
65     */
66    public function setLog($log)
67    {
68        $this->_log = $log;
69
70        return $this;
71    }
72
73    /**
74     * Return last logged message.
75     *
76     * @return string Last logged message
77     */
78    public function getLastMessage()
79    {
80        return $this->_lastMessage;
81    }
82}
83