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