Fix object handling inside log arrays
[friendica.git/.git] / src / Util / Logger / StreamLogger.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util\Logger;
23
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\FileSystem;
26 use Friendica\Util\Introspection;
27 use Psr\Log\LogLevel;
28
29 /**
30  * A Logger instance for logging into a stream (file, stdout, stderr)
31  */
32 class StreamLogger extends AbstractLogger
33 {
34         /**
35          * The minimum loglevel at which this logger will be triggered
36          * @var string
37          */
38         private $logLevel;
39
40         /**
41          * The file URL of the stream (if needed)
42          * @var string
43          */
44         private $url;
45
46         /**
47          * The stream, where the current logger is writing into
48          * @var resource
49          */
50         private $stream;
51
52         /**
53          * The current process ID
54          * @var int
55          */
56         private $pid;
57
58         /**
59          * @var FileSystem
60          */
61         private $fileSystem;
62
63         /**
64          * Translates LogLevel log levels to integer values
65          * @var array
66          */
67         private $levelToInt = [
68                 LogLevel::EMERGENCY => 0,
69                 LogLevel::ALERT     => 1,
70                 LogLevel::CRITICAL  => 2,
71                 LogLevel::ERROR     => 3,
72                 LogLevel::WARNING   => 4,
73                 LogLevel::NOTICE    => 5,
74                 LogLevel::INFO      => 6,
75                 LogLevel::DEBUG     => 7,
76         ];
77
78         /**
79          * {@inheritdoc}
80          * @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
81          * @param string          $level  The minimum loglevel at which this logger will be triggered
82          *
83          * @throws \Exception
84          */
85         public function __construct($channel, $stream, Introspection $introspection, FileSystem $fileSystem, $level = LogLevel::DEBUG)
86         {
87                 $this->fileSystem = $fileSystem;
88
89                 parent::__construct($channel, $introspection);
90
91                 if (is_resource($stream)) {
92                         $this->stream = $stream;
93                 } elseif (is_string($stream)) {
94                         $this->url = $stream;
95                 } else {
96                         throw new \InvalidArgumentException('A stream must either be a resource or a string.');
97                 }
98
99                 $this->pid = getmypid();
100                 if (array_key_exists($level, $this->levelToInt)) {
101                         $this->logLevel = $this->levelToInt[$level];
102                 } else {
103                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
104                 }
105
106                 $this->checkStream();
107         }
108
109         public function close()
110         {
111                 if ($this->url && is_resource($this->stream)) {
112                         fclose($this->stream);
113                 }
114
115                 $this->stream = null;
116         }
117
118         /**
119          * Adds a new entry to the log
120          *
121          * @param int $level
122          * @param string $message
123          * @param array $context
124          *
125          * @return void
126          */
127         protected function addEntry($level, $message, $context = [])
128         {
129                 if (!array_key_exists($level, $this->levelToInt)) {
130                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
131                 }
132
133                 $logLevel = $this->levelToInt[$level];
134
135                 if ($logLevel > $this->logLevel) {
136                         return;
137                 }
138
139                 $this->checkStream();
140
141                 $formattedLog = $this->formatLog($level, $message, $context);
142                 fwrite($this->stream, $formattedLog);
143         }
144
145         /**
146          * Formats a log record for the syslog output
147          *
148          * @param int    $level   The loglevel/priority
149          * @param string $message The message
150          * @param array  $context The context of this call
151          *
152          * @return string the formatted syslog output
153          */
154         private function formatLog($level, $message, $context = [])
155         {
156                 $record = $this->introspection->getRecord();
157                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
158                 $logMessage = '';
159
160                 $logMessage .= DateTimeFormat::utcNow(DateTimeFormat::ATOM) . ' ';
161                 $logMessage .= $this->channel . ' ';
162                 $logMessage .= '[' . strtoupper($level) . ']: ';
163                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
164                 $logMessage .= $this->jsonEncodeArray($context) . ' - ';
165                 $logMessage .= $this->jsonEncodeArray($record);
166                 $logMessage .= PHP_EOL;
167
168                 return $logMessage;
169         }
170
171         private function checkStream()
172         {
173                 if (is_resource($this->stream)) {
174                         return;
175                 }
176
177                 if (empty($this->url)) {
178                         throw new \LogicException('Missing stream URL.');
179                 }
180
181                 $this->stream = $this->fileSystem->createStream($this->url);
182         }
183 }