Added StreamLoggerTest
[friendica.git/.git] / src / Util / Logger / StreamLogger.php
1 <?php
2
3 namespace Friendica\Util\Logger;
4
5 use Friendica\Util\DateTimeFormat;
6 use Friendica\Util\Introspection;
7 use Psr\Log\LogLevel;
8
9 /**
10  * A Logger instance for logging into a stream (file, stdout, stderr)
11  */
12 class StreamLogger extends AbstractFriendicaLogger
13 {
14         /**
15          * The minimum loglevel at which this logger will be triggered
16          * @var string
17          */
18         private $logLevel;
19
20         /**
21          * The file URL of the stream (if needed)
22          * @var string
23          */
24         private $url;
25
26         /**
27          * The stream, where the current logger is writing into
28          * @var resource
29          */
30         private $stream;
31
32         /**
33          * The current process ID
34          * @var int
35          */
36         private $pid;
37
38         /**
39          * An error message
40          * @var string
41          */
42         private $errorMessage;
43
44         /**
45          * Translates LogLevel log levels to integer values
46          * @var array
47          */
48         private $levelToInt = [
49                 LogLevel::EMERGENCY => 0,
50                 LogLevel::ALERT     => 1,
51                 LogLevel::CRITICAL  => 2,
52                 LogLevel::ERROR     => 3,
53                 LogLevel::WARNING   => 4,
54                 LogLevel::NOTICE    => 5,
55                 LogLevel::INFO      => 6,
56                 LogLevel::DEBUG     => 7,
57         ];
58
59         /**
60          * {@inheritdoc}
61          * @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
62          * @param string          $level  The minimum loglevel at which this logger will be triggered
63          *
64          * @throws \Exception
65          */
66         public function __construct($channel, $stream, Introspection $introspection, $level = LogLevel::DEBUG)
67         {
68                 parent::__construct($channel, $introspection);
69
70                 if (is_resource($stream)) {
71                         $this->stream = $stream;
72                 } elseif (is_string($stream)) {
73                         $this->url = $stream;
74                 } else {
75                         throw new \InvalidArgumentException('A stream must either be a resource or a string.');
76                 }
77
78                 $this->pid = getmypid();
79                 if (array_key_exists($level, $this->levelToInt)) {
80                         $this->logLevel = $this->levelToInt[$level];
81                 } else {
82                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
83                 }
84         }
85
86         public function close()
87         {
88                 if ($this->url && is_resource($this->stream)) {
89                         fclose($this->stream);
90                 }
91
92                 $this->stream = null;
93         }
94
95         /**
96          * Adds a new entry to the log
97          *
98          * @param int $level
99          * @param string $message
100          * @param array $context
101          *
102          * @return void
103          */
104         protected function addEntry($level, $message, $context = [])
105         {
106                 if (!array_key_exists($level, $this->levelToInt)) {
107                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
108                 }
109
110                 $logLevel = $this->levelToInt[$level];
111
112                 if ($logLevel > $this->logLevel) {
113                         return;
114                 }
115
116                 $this->checkStream();
117
118                 $this->stream = fopen($this->url, 'a');
119                 $formattedLog = $this->formatLog($level, $message, $context);
120                 fwrite($this->stream, $formattedLog);
121         }
122
123         /**
124          * Formats a log record for the syslog output
125          *
126          * @param int    $level   The loglevel/priority
127          * @param string $message The message
128          * @param array  $context The context of this call
129          *
130          * @return string the formatted syslog output
131          */
132         private function formatLog($level, $message, $context = [])
133         {
134                 $record = $this->introspection->getRecord();
135                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
136                 $logMessage = '';
137
138                 $logMessage .= DateTimeFormat::localNow() . ' ';
139                 $logMessage .= $this->channel . ' ';
140                 $logMessage .= '[' . strtoupper($level) . ']: ';
141                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
142                 $logMessage .= @json_encode($context) . ' - ';
143                 $logMessage .= @json_encode($record);
144                 $logMessage .= PHP_EOL;
145
146                 return $logMessage;
147         }
148
149         private function checkStream()
150         {
151                 if (is_resource($this->stream)) {
152                         return;
153                 }
154
155                 if (empty($this->url)) {
156                         throw new \LogicException('Missing stream URL.');
157                 }
158
159                 $this->createDir();
160                 set_error_handler([$this, 'customErrorHandler']);
161                 $this->stream = fopen($this->url, 'ab');
162                 restore_error_handler();
163
164                 if (!is_resource($this->stream)) {
165                         $this->stream = null;
166
167                         throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
168                 }
169         }
170
171         private function createDir()
172         {
173                 $dirname = null;
174                 $pos = strpos($this->url, '://');
175                 if (!$pos) {
176                         $dirname = dirname($this->url);
177                 }
178
179                 if (substr($this->url, 0, 7) === 'file://') {
180                         $dirname = dirname(substr($this->url, 7));
181                 }
182
183                 if (isset($dirname) && !is_dir($dirname)) {
184                         set_error_handler([$this, 'customErrorHandler']);
185                         $status = mkdir($dirname, 0777, true);
186                         restore_error_handler();
187
188                         if (!$status && !is_dir($dirname)) {
189                                 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
190                         }
191                 }
192         }
193
194         private function customErrorHandler($code, $msg)
195         {
196                 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
197         }
198 }