]> git.mxchange.org Git - friendica.git/blob - src/Core/Logger/Factory/Logger.php
Replace own VoidLogger with PSR-Standard NullLogger()
[friendica.git] / src / Core / Logger / Factory / Logger.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\Factory;
23
24 use Friendica\Core\Config\Capability\IManageConfigValues;
25 use Friendica\Core\Logger\Exception\LoggerException;
26 use Friendica\Core;
27 use Friendica\Database\Database;
28 use Friendica\Util\FileSystem;
29 use Friendica\Util\Introspection;
30 use Friendica\Core\Logger\Type\Monolog\DevelopHandler;
31 use Friendica\Core\Logger\Type\Monolog\IntrospectionProcessor;
32 use Friendica\Core\Logger\Type\ProfilerLogger;
33 use Friendica\Core\Logger\Type\StreamLogger;
34 use Friendica\Core\Logger\Type\SyslogLogger;
35 use Friendica\Util\Profiler;
36 use Monolog;
37 use Psr\Log\LoggerInterface;
38 use Psr\Log\LogLevel;
39 use Psr\Log\NullLogger;
40
41 /**
42  * A logger factory
43  */
44 class Logger
45 {
46         const DEV_CHANNEL = 'dev';
47
48         /**
49          * A list of classes, which shouldn't get logged
50          *
51          * @var string[]
52          */
53         private static $ignoreClassList = [
54                 Core\Logger::class,
55                 Profiler::class,
56                 'Friendica\\Core\\Logger\\Type',
57                 'Friendica\\Core\\Logger\\Type\\Monolog',
58         ];
59
60         /** @var string The log-channel (app, worker, ...) */
61         private $channel;
62
63         public function __construct(string $channel)
64         {
65                 $this->channel = $channel;
66         }
67
68         /**
69          * Creates a new PSR-3 compliant logger instances
70          *
71          * @param Database            $database   The Friendica Database instance
72          * @param IManageConfigValues $config     The config
73          * @param Profiler            $profiler   The profiler of the app
74          * @param FileSystem          $fileSystem FileSystem utils
75          *
76          * @return LoggerInterface The PSR-3 compliant logger instance
77          */
78         public function create(Database $database, IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem): LoggerInterface
79         {
80                 if (empty($config->get('system', 'debugging', false))) {
81                         $logger = new NullLogger();
82                         $database->setLogger($logger);
83                         return $logger;
84                 }
85
86                 $introspection = new Introspection(self::$ignoreClassList);
87                 $level         = $config->get('system', 'loglevel');
88                 $loglevel      = self::mapLegacyConfigDebugLevel((string)$level);
89
90                 switch ($config->get('system', 'logger_config', 'stream')) {
91                         case 'monolog':
92                                 $loggerTimeZone = new \DateTimeZone('UTC');
93                                 Monolog\Logger::setTimezone($loggerTimeZone);
94
95                                 $logger = new Monolog\Logger($this->channel);
96                                 $logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
97                                 $logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
98                                 $logger->pushProcessor(new Monolog\Processor\UidProcessor());
99                                 $logger->pushProcessor(new IntrospectionProcessor($introspection, LogLevel::DEBUG));
100
101                                 $stream = $config->get('system', 'logfile');
102
103                                 // just add a stream in case it's either writable or not file
104                                 if (!is_file($stream) || is_writable($stream)) {
105                                         try {
106                                                 static::addStreamHandler($logger, $stream, $loglevel);
107                                         } catch (\Throwable $e) {
108                                                 // No Logger ..
109                                                 /// @todo isn't it possible to give the admin any hint about this wrong configuration?
110                                                 $logger = new NullLogger();
111                                         }
112                                 }
113                                 break;
114
115                         case 'syslog':
116                                 try {
117                                         $logger = new SyslogLogger($this->channel, $introspection, $loglevel);
118                                 } catch (\Throwable $e) {
119                                         // No logger ...
120                                         /// @todo isn't it possible to give the admin any hint about this wrong configuration?
121                                         $logger = new NullLogger();
122                                 }
123                                 break;
124
125                         case 'stream':
126                         default:
127                                 $stream = $config->get('system', 'logfile');
128                                 // just add a stream in case it's either writable or not file
129                                 if (!is_file($stream) || is_writable($stream)) {
130                                         try {
131                                                 $logger = new StreamLogger($this->channel, $stream, $introspection, $fileSystem, $loglevel);
132                                         } catch (\Throwable $t) {
133                                                 // No logger ...
134                                                 /// @todo isn't it possible to give the admin any hint about this wrong configuration?
135                                                 $logger = new NullLogger();
136                                         }
137                                 } else {
138                                         /// @todo isn't it possible to give the admin any hint about this wrong configuration?
139                                         $logger = new NullLogger();
140                                 }
141                                 break;
142                 }
143
144                 $profiling = $config->get('system', 'profiling', false);
145
146                 // In case profiling is enabled, wrap the ProfilerLogger around the current logger
147                 if (isset($profiling) && $profiling !== false) {
148                         $logger = new ProfilerLogger($logger, $profiler);
149                 }
150
151                 $database->setLogger($logger);
152                 return $logger;
153         }
154
155         /**
156          * Creates a new PSR-3 compliant develop logger
157          *
158          * If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
159          * you'll use this logger instance for the duration of your work.
160          *
161          * It should never get filled during normal usage of Friendica
162          *
163          * @param IManageConfigValues $config     The config
164          * @param Profiler            $profiler   The profiler of the app
165          * @param FileSystem          $fileSystem FileSystem utils
166          *
167          * @return LoggerInterface The PSR-3 compliant logger instance
168          * @throws \Exception
169          */
170         public static function createDev(IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
171         {
172                 $debugging   = $config->get('system', 'debugging');
173                 $stream      = $config->get('system', 'dlogfile');
174                 $developerIp = $config->get('system', 'dlogip');
175
176                 if ((!isset($developerIp) || !$debugging) &&
177                         (!is_file($stream) || is_writable($stream))) {
178                         return new NullLogger();
179                 }
180
181                 $loggerTimeZone = new \DateTimeZone('UTC');
182                 Monolog\Logger::setTimezone($loggerTimeZone);
183
184                 $introspection = new Introspection(self::$ignoreClassList);
185
186                 switch ($config->get('system', 'logger_config', 'stream')) {
187
188                         case 'monolog':
189                                 $loggerTimeZone = new \DateTimeZone('UTC');
190                                 Monolog\Logger::setTimezone($loggerTimeZone);
191
192                                 $logger = new Monolog\Logger(self::DEV_CHANNEL);
193                                 $logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
194                                 $logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
195                                 $logger->pushProcessor(new Monolog\Processor\UidProcessor());
196                                 $logger->pushProcessor(new IntrospectionProcessor($introspection, LogLevel::DEBUG));
197
198                                 $logger->pushHandler(new DevelopHandler($developerIp));
199
200                                 static::addStreamHandler($logger, $stream, LogLevel::DEBUG);
201                                 break;
202
203                         case 'syslog':
204                                 $logger = new SyslogLogger(self::DEV_CHANNEL, $introspection, LogLevel::DEBUG);
205                                 break;
206
207                         case 'stream':
208                         default:
209                                 $logger = new StreamLogger(self::DEV_CHANNEL, $stream, $introspection, $fileSystem, LogLevel::DEBUG);
210                                 break;
211                 }
212
213                 $profiling = $config->get('system', 'profiling', false);
214
215                 // In case profiling is enabled, wrap the ProfilerLogger around the current logger
216                 if (isset($profiling) && $profiling !== false) {
217                         $logger = new ProfilerLogger($logger, $profiler);
218                 }
219
220                 return $logger;
221         }
222
223         /**
224          * Mapping a legacy level to the PSR-3 compliant levels
225          *
226          * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
227          *
228          * @param string $level the level to be mapped
229          *
230          * @return string the PSR-3 compliant level
231          */
232         private static function mapLegacyConfigDebugLevel(string $level): string
233         {
234                 switch ($level) {
235                         // legacy WARNING
236                         case "0":
237                                 return LogLevel::ERROR;
238                         // legacy INFO
239                         case "1":
240                                 return LogLevel::WARNING;
241                         // legacy TRACE
242                         case "2":
243                                 return LogLevel::NOTICE;
244                         // legacy DEBUG
245                         case "3":
246                                 return LogLevel::INFO;
247                         // legacy DATA
248                         case "4":
249                         // legacy ALL
250                         case "5":
251                                 return LogLevel::DEBUG;
252                         // default if nothing set
253                         default:
254                                 return $level;
255                 }
256         }
257
258         /**
259          * Adding a handler to a given logger instance
260          *
261          * @param LoggerInterface $logger The logger instance
262          * @param mixed           $stream The stream which handles the logger output
263          * @param string          $level  The level, for which this handler at least should handle logging
264          *
265          * @return void
266          *
267          * @throws LoggerException
268          */
269         public static function addStreamHandler(LoggerInterface $logger, $stream, string $level = LogLevel::NOTICE)
270         {
271                 if ($logger instanceof Monolog\Logger) {
272                         $loglevel = Monolog\Logger::toMonologLevel($level);
273
274                         // fallback to notice if an invalid loglevel is set
275                         if (!is_int($loglevel)) {
276                                 $loglevel = LogLevel::NOTICE;
277                         }
278
279                         try {
280                                 $fileHandler = new Monolog\Handler\StreamHandler($stream, $loglevel);
281
282                                 $formatter = new Monolog\Formatter\LineFormatter("%datetime% %channel% [%level_name%]: %message% %context% %extra%\n");
283                                 $fileHandler->setFormatter($formatter);
284
285                                 $logger->pushHandler($fileHandler);
286                         } catch (\Exception $exception) {
287                                 throw new LoggerException('Cannot create Monolog Logger.', $exception);
288                         }
289                 }
290         }
291 }