]> git.mxchange.org Git - friendica.git/blob - src/Core/Logger/Factory/Logger.php
Move Monolog to Addons
[friendica.git] / src / Core / Logger / Factory / Logger.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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;
26 use Friendica\Core\Logger\Exception\LogLevelException;
27 use Friendica\Database\Database;
28 use Friendica\Network\HTTPException\InternalServerErrorException;
29 use Friendica\Util\FileSystem;
30 use Friendica\Core\Logger\Util\Introspection;
31 use Friendica\Core\Logger\Type\ProfilerLogger;
32 use Friendica\Core\Logger\Type\StreamLogger;
33 use Friendica\Core\Logger\Type\SyslogLogger;
34 use Friendica\Util\Profiler;
35 use Psr\Log\LoggerInterface;
36 use Psr\Log\LogLevel;
37 use Psr\Log\NullLogger;
38
39 /**
40  * A logger factory
41  */
42 class Logger
43 {
44         const DEV_CHANNEL = 'dev';
45
46         /**
47          * A list of classes, which shouldn't get logged
48          *
49          * @var string[]
50          */
51         private static $ignoreClassList = [
52                 Core\Logger::class,
53                 Profiler::class,
54                 'Friendica\\Core\\Logger\\Type',
55         ];
56
57         /** @var string The log-channel (app, worker, ...) */
58         private $channel;
59
60         public function __construct(string $channel, bool $includeAddon = true)
61         {
62                 $this->channel = $channel;
63
64                 /// @fixme clean solution = Making Addon & Hook dynamic and load them inside the constructor, so there's no custom load logic necessary anymore
65                 if ($includeAddon) {
66                         Core\Addon::loadAddons();
67                         Core\Hook::loadHooks();
68                 }
69         }
70
71         /**
72          * Creates a new PSR-3 compliant logger instances
73          *
74          * @param Database            $database   The Friendica Database instance
75          * @param IManageConfigValues $config     The config
76          * @param Profiler            $profiler   The profiler of the app
77          * @param FileSystem          $fileSystem FileSystem utils
78          * @param string|null         $minLevel   (optional) Override minimum Loglevel to log
79          *
80          * @return LoggerInterface The PSR-3 compliant logger instance
81          */
82         public function create(Database $database, IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem, ?string $minLevel = null): LoggerInterface
83         {
84                 if (empty($config->get('system', 'debugging', false))) {
85                         $logger = new NullLogger();
86                         $database->setLogger($logger);
87                         return $logger;
88                 }
89
90                 $introspection = new Introspection(self::$ignoreClassList);
91                 $minLevel      = $minLevel ?? $config->get('system', 'loglevel');
92                 $loglevel      = self::mapLegacyConfigDebugLevel((string)$minLevel);
93
94                 $name = $config->get('system', 'logger_config', 'stream');
95
96                 switch ($name) {
97                         case 'syslog':
98                                 try {
99                                         $logger = new SyslogLogger($this->channel, $introspection, $loglevel, $config->get('system', 'syslog_flags', SyslogLogger::DEFAULT_FLAGS), $config->get('system', 'syslog_facility', SyslogLogger::DEFAULT_FACILITY));
100                                 } catch (LogLevelException $exception) {
101                                         // If there's a wrong config value for loglevel, try again with standard
102                                         $logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
103                                         $logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
104                                 } catch (\Throwable $e) {
105                                         // No logger ...
106                                         $logger = new NullLogger();
107                                 }
108                                 break;
109
110                         case 'stream':
111                         default:
112                                 $data = [
113                                         'name'          => $name,
114                                         'channel'       => $this->channel,
115                                         'introspection' => $introspection,
116                                         'loglevel'      => $loglevel,
117                                         'logger'        => null,
118                                 ];
119                                 try {
120                                         Core\Hook::callAll('logger_instance', $data);
121                                 } catch (InternalServerErrorException $exception) {
122                                         $data['logger'] = null;
123                                 }
124
125                                 if (($data['logger'] ?? null) instanceof LoggerInterface) {
126                                         $logger = $data['logger'];
127                                 }
128
129                                 if (empty($logger)) {
130                                         $stream = $config->get('system', 'logfile');
131                                         // just add a stream in case it's either writable or not file
132                                         if (!is_file($stream) || is_writable($stream)) {
133                                                 try {
134                                                         $logger = new StreamLogger($this->channel, $stream, $introspection, $fileSystem, $loglevel);
135                                                 } catch (LogLevelException $exception) {
136                                                         // If there's a wrong config value for loglevel, try again with standard
137                                                         $logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
138                                                         $logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
139                                                 } catch (\Throwable $t) {
140                                                         // No logger ...
141                                                         $logger = new NullLogger();
142                                                 }
143                                         } else {
144                                                 try {
145                                                         $logger = new SyslogLogger($this->channel, $introspection, $loglevel);
146                                                 } catch (LogLevelException $exception) {
147                                                         // If there's a wrong config value for loglevel, try again with standard
148                                                         $logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
149                                                         $logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
150                                                 } catch (\Throwable $e) {
151                                                         // No logger ...
152                                                         $logger = new NullLogger();
153                                                 }
154                                         }
155                                 }
156                                 break;
157                 }
158
159                 $profiling = $config->get('system', 'profiling', false);
160
161                 // In case profiling is enabled, wrap the ProfilerLogger around the current logger
162                 if (isset($profiling) && $profiling !== false) {
163                         $logger = new ProfilerLogger($logger, $profiler);
164                 }
165
166                 $database->setLogger($logger);
167                 return $logger;
168         }
169
170         /**
171          * Creates a new PSR-3 compliant develop logger
172          *
173          * If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
174          * you'll use this logger instance for the duration of your work.
175          *
176          * It should never get filled during normal usage of Friendica
177          *
178          * @param IManageConfigValues $config     The config
179          * @param Profiler            $profiler   The profiler of the app
180          * @param FileSystem          $fileSystem FileSystem utils
181          *
182          * @return LoggerInterface The PSR-3 compliant logger instance
183          * @throws \Exception
184          */
185         public static function createDev(IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
186         {
187                 $debugging   = $config->get('system', 'debugging');
188                 $stream      = $config->get('system', 'dlogfile');
189                 $developerIp = $config->get('system', 'dlogip');
190
191                 if ((!isset($developerIp) || !$debugging) &&
192                         (!is_file($stream) || is_writable($stream))) {
193                         return new NullLogger();
194                 }
195
196                 $introspection = new Introspection(self::$ignoreClassList);
197
198                 $name = $config->get('system', 'logger_config', 'stream');
199
200                 switch ($name) {
201
202                         case 'syslog':
203                                 $logger = new SyslogLogger(self::DEV_CHANNEL, $introspection, LogLevel::DEBUG);
204                                 break;
205
206                         case 'stream':
207                         default:
208                                 $data = [
209                                         'name'          => $name,
210                                         'channel'       => self::DEV_CHANNEL,
211                                         'introspection' => $introspection,
212                                         'loglevel'      => LogLevel::DEBUG,
213                                         'logger'        => null,
214                                 ];
215                                 try {
216                                         Core\Hook::callAll('logger_instance', $data);
217                                 } catch (InternalServerErrorException $exception) {
218                                         $data['logger'] = null;
219                                 }
220
221                                 if (($data['logger'] ?? null) instanceof LoggerInterface) {
222                                         return $data['logger'];
223                                 }
224
225                                 $logger = new StreamLogger(self::DEV_CHANNEL, $stream, $introspection, $fileSystem, LogLevel::DEBUG);
226                                 break;
227                 }
228
229                 $profiling = $config->get('system', 'profiling', false);
230
231                 // In case profiling is enabled, wrap the ProfilerLogger around the current logger
232                 if (isset($profiling) && $profiling !== false) {
233                         $logger = new ProfilerLogger($logger, $profiler);
234                 }
235
236                 return $logger;
237         }
238
239         /**
240          * Mapping a legacy level to the PSR-3 compliant levels
241          *
242          * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
243          *
244          * @param string $level the level to be mapped
245          *
246          * @return string the PSR-3 compliant level
247          */
248         private static function mapLegacyConfigDebugLevel(string $level): string
249         {
250                 switch ($level) {
251                         // legacy WARNING
252                         case "0":
253                                 return LogLevel::ERROR;
254                         // legacy INFO
255                         case "1":
256                                 return LogLevel::WARNING;
257                         // legacy TRACE
258                         case "2":
259                                 return LogLevel::NOTICE;
260                         // legacy DEBUG
261                         case "3":
262                                 return LogLevel::INFO;
263                         // legacy DATA
264                         case "4":
265                         // legacy ALL
266                         case "5":
267                                 return LogLevel::DEBUG;
268                         // default if nothing set
269                         default:
270                                 return $level;
271                 }
272         }
273 }