]> git.mxchange.org Git - friendica.git/blob - src/Core/Logger/Type/StreamLogger.php
Merge pull request #10921 from nupplaphil/feat/httpclient_restructuring
[friendica.git] / src / Core / Logger / Type / StreamLogger.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\Core\Logger\Type;
23
24 use Friendica\Core\Logger\Exception\LoggerArgumentException;
25 use Friendica\Core\Logger\Exception\LoggerException;
26 use Friendica\Core\Logger\Exception\LogLevelException;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\FileSystem;
29 use Friendica\Core\Logger\Util\Introspection;
30 use Psr\Log\LogLevel;
31
32 /**
33  * A Logger instance for logging into a stream (file, stdout, stderr)
34  */
35 class StreamLogger extends AbstractLogger
36 {
37         /**
38          * The minimum loglevel at which this logger will be triggered
39          * @var string
40          */
41         private $logLevel;
42
43         /**
44          * The file URL of the stream (if needed)
45          * @var string
46          */
47         private $url;
48
49         /**
50          * The stream, where the current logger is writing into
51          * @var resource
52          */
53         private $stream;
54
55         /**
56          * The current process ID
57          * @var int
58          */
59         private $pid;
60
61         /**
62          * @var FileSystem
63          */
64         private $fileSystem;
65
66         /**
67          * Translates LogLevel log levels to integer values
68          * @var array
69          */
70         private $levelToInt = [
71                 LogLevel::EMERGENCY => 0,
72                 LogLevel::ALERT     => 1,
73                 LogLevel::CRITICAL  => 2,
74                 LogLevel::ERROR     => 3,
75                 LogLevel::WARNING   => 4,
76                 LogLevel::NOTICE    => 5,
77                 LogLevel::INFO      => 6,
78                 LogLevel::DEBUG     => 7,
79         ];
80
81         /**
82          * {@inheritdoc}
83          * @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
84          * @param string          $level  The minimum loglevel at which this logger will be triggered
85          *
86          * @throws LoggerArgumentException
87          * @throws LogLevelException
88          */
89         public function __construct($channel, $stream, Introspection $introspection, FileSystem $fileSystem, string $level = LogLevel::DEBUG)
90         {
91                 $this->fileSystem = $fileSystem;
92
93                 parent::__construct($channel, $introspection);
94
95                 if (is_resource($stream)) {
96                         $this->stream = $stream;
97                 } elseif (is_string($stream)) {
98                         $this->url = $stream;
99                 } else {
100                         throw new LoggerArgumentException('A stream must either be a resource or a string.');
101                 }
102
103                 $this->pid = getmypid();
104                 if (array_key_exists($level, $this->levelToInt)) {
105                         $this->logLevel = $this->levelToInt[$level];
106                 } else {
107                         throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
108                 }
109
110                 $this->checkStream();
111         }
112
113         public function close()
114         {
115                 if ($this->url && is_resource($this->stream)) {
116                         fclose($this->stream);
117                 }
118
119                 $this->stream = null;
120         }
121
122         /**
123          * Adds a new entry to the log
124          *
125          * @param mixed  $level
126          * @param string $message
127          * @param array  $context
128          *
129          * @return void
130          *
131          * @throws LoggerException
132          * @throws LogLevelException
133          */
134         protected function addEntry($level, string $message, array $context = [])
135         {
136                 if (!array_key_exists($level, $this->levelToInt)) {
137                         throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
138                 }
139
140                 $logLevel = $this->levelToInt[$level];
141
142                 if ($logLevel > $this->logLevel) {
143                         return;
144                 }
145
146                 $this->checkStream();
147
148                 $formattedLog = $this->formatLog($level, $message, $context);
149                 fwrite($this->stream, $formattedLog);
150         }
151
152         /**
153          * Formats a log record for the syslog output
154          *
155          * @param mixed  $level   The loglevel/priority
156          * @param string $message The message
157          * @param array  $context The context of this call
158          *
159          * @return string the formatted syslog output
160          *
161          * @throws LoggerException
162          */
163         private function formatLog($level, string $message, array $context = []): string
164         {
165                 $record = $this->introspection->getRecord();
166                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
167
168                 try {
169                         $logMessage = DateTimeFormat::utcNow(DateTimeFormat::ATOM) . ' ';
170                 } catch (\Exception $exception) {
171                         throw new LoggerException('Cannot get current datetime.', $exception);
172                 }
173                 $logMessage .= $this->channel . ' ';
174                 $logMessage .= '[' . strtoupper($level) . ']: ';
175                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
176                 $logMessage .= $this->jsonEncodeArray($context) . ' - ';
177                 $logMessage .= $this->jsonEncodeArray($record);
178                 $logMessage .= PHP_EOL;
179
180                 return $logMessage;
181         }
182
183         /**
184          * Checks the current stream
185          *
186          * @throws LoggerException
187          * @throws LoggerArgumentException
188          */
189         private function checkStream()
190         {
191                 if (is_resource($this->stream)) {
192                         return;
193                 }
194
195                 if (empty($this->url)) {
196                         throw new LoggerArgumentException('Missing stream URL.');
197                 }
198
199                 try {
200                         $this->stream = $this->fileSystem->createStream($this->url);
201                 } catch (\UnexpectedValueException $exception) {
202                         throw new LoggerException('Cannot create stream.', $exception);
203                 }
204         }
205 }