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