Browse Source

Adding Develop and normal Logging instances

tags/2019.03^2
Philipp Holzer 6 months ago
parent
commit
8f9c0fe149

+ 2
- 2
bin/auth_ejabberd.php View File

@@ -33,8 +33,8 @@
33 33
  */
34 34
 
35 35
 use Friendica\App;
36
-use Friendica\Core\Logger;
37 36
 use Friendica\Util\ExAuth;
37
+use Friendica\Util\LoggerFactory;
38 38
 
39 39
 if (sizeof($_SERVER["argv"]) == 0) {
40 40
 	die();
@@ -52,7 +52,7 @@ chdir($directory);
52 52
 
53 53
 require dirname(__DIR__) . '/vendor/autoload.php';
54 54
 
55
-$logger = Logger::create('ejabberd');
55
+$logger = LoggerFactory::create('auth_ejabberd');
56 56
 
57 57
 $a = new App(dirname(__DIR__), $logger);
58 58
 

+ 2
- 2
bin/console.php View File

@@ -3,9 +3,9 @@
3 3
 
4 4
 require dirname(__DIR__) . '/vendor/autoload.php';
5 5
 
6
-use Friendica\Core\Logger;
6
+use Friendica\Util\LoggerFactory;
7 7
 
8
-$logger = Logger::create('console');
8
+$logger = LoggerFactory::create('console');
9 9
 
10 10
 $a = new Friendica\App(dirname(__DIR__), $logger);
11 11
 \Friendica\BaseObject::setApp($a);

+ 2
- 2
bin/daemon.php View File

@@ -9,9 +9,9 @@
9 9
 
10 10
 use Friendica\App;
11 11
 use Friendica\Core\Config;
12
-use Friendica\Core\Logger;
13 12
 use Friendica\Core\Worker;
14 13
 use Friendica\Database\DBA;
14
+use Friendica\Util\LoggerFactory;
15 15
 
16 16
 // Get options
17 17
 $shortopts = 'f';
@@ -32,7 +32,7 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
32 32
 
33 33
 require dirname(__DIR__) . '/vendor/autoload.php';
34 34
 
35
-$logger = Logger::create('daemon');
35
+$logger = LoggerFactory::create('daemon');
36 36
 
37 37
 $a = new App(dirname(__DIR__), $logger);
38 38
 

+ 2
- 2
bin/worker.php View File

@@ -6,9 +6,9 @@
6 6
  */
7 7
 use Friendica\App;
8 8
 use Friendica\Core\Config;
9
-use Friendica\Core\Logger;
10 9
 use Friendica\Core\Worker;
11 10
 use Friendica\Core\Update;
11
+use Friendica\Util\LoggerFactory;
12 12
 
13 13
 // Get options
14 14
 $shortopts = 'sn';
@@ -29,7 +29,7 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
29 29
 
30 30
 require dirname(__DIR__) . '/vendor/autoload.php';
31 31
 
32
-$logger = Logger::create('worker');
32
+$logger = LoggerFactory::create('worker');
33 33
 
34 34
 $a = new App(dirname(__DIR__), $logger);
35 35
 

+ 2
- 2
index.php View File

@@ -5,7 +5,7 @@
5 5
  */
6 6
 
7 7
 use Friendica\App;
8
-use Friendica\Core\Logger;
8
+use Friendica\Util\LoggerFactory;
9 9
 
10 10
 if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
11 11
 	die('Vendor path not found. Please execute "bin/composer.phar --no-dev install" on the command line in the web root.');
@@ -13,7 +13,7 @@ if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
13 13
 
14 14
 require __DIR__ . '/vendor/autoload.php';
15 15
 
16
-$logger = Logger::create('app');
16
+$logger = LoggerFactory::create('app');
17 17
 
18 18
 // We assume that the index.php is called by a frontend process
19 19
 // The value is set to "true" by default in App

+ 7
- 8
src/App.php View File

@@ -8,10 +8,9 @@ use Detection\MobileDetect;
8 8
 use DOMDocument;
9 9
 use DOMXPath;
10 10
 use Exception;
11
-use Friendica\Core\Logger;
12 11
 use Friendica\Database\DBA;
13 12
 use Friendica\Network\HTTPException\InternalServerErrorException;
14
-use Monolog;
13
+use Psr\Log\LoggerInterface;
15 14
 
16 15
 /**
17 16
  *
@@ -109,7 +108,7 @@ class App
109 108
 	public $mobileDetect;
110 109
 
111 110
 	/**
112
-	 * @var Monolog\Logger The current logger of this App
111
+	 * @var LoggerInterface The current logger of this App
113 112
 	 */
114 113
 	private $logger;
115 114
 
@@ -153,9 +152,9 @@ class App
153 152
 	/**
154 153
 	 * @brief App constructor.
155 154
 	 *
156
-	 * @param string $basePath  Path to the app base folder
157
-	 * @param Monolog\Logger    Logger of this application
158
-	 * @param bool   $isBackend Whether it is used for backend or frontend (Default true=backend)
155
+	 * @param string           $basePath  Path to the app base folder
156
+	 * @param LoggerInterface  $logger    Logger of this application
157
+	 * @param bool             $isBackend Whether it is used for backend or frontend (Default true=backend)
159 158
 	 *
160 159
 	 * @throws Exception if the Basepath is not usable
161 160
 	 */
@@ -314,7 +313,7 @@ class App
314 313
 	/**
315 314
 	 * Returns the Logger of the Application
316 315
 	 *
317
-	 * @return Monolog\Logger The Logger
316
+	 * @return LoggerInterface The Logger
318 317
 	 * @throws InternalServerErrorException when the logger isn't created
319 318
 	 */
320 319
 	public function getLogger()
@@ -354,7 +353,7 @@ class App
354 353
 
355 354
 		$this->process_id = Core\System::processID('log');
356 355
 
357
-		Logger::loadDefaultHandler($this->logger, $this);
356
+		Core\Logger::setLogger($this->logger);
358 357
 	}
359 358
 
360 359
 	/**

+ 0
- 48
src/App/FriendicaLoggerProcessor.php View File

@@ -1,48 +0,0 @@
1
-<?php
2
-
3
-namespace Friendica\App;
4
-
5
-use Monolog\Processor\ProcessorInterface;
6
-
7
-/**
8
- * Includes the Friendica specific process_id of "app->process_id"
9
- *
10
- * @package Friendica\App
11
- */
12
-class FriendicaLoggerProcessor implements ProcessorInterface
13
-{
14
-	/**
15
-	 * @var string the ID of the current Friendica process
16
-	 */
17
-	private $processId = null;
18
-
19
-	/**
20
-	 * Set the process id based on the Application instance
21
-	 *
22
-	 * @param string $processId the process id
23
-	 */
24
-	public function setProcessId($processId)
25
-	{
26
-		if (!isset($this->processId) || $this->processId == '')
27
-		{
28
-			$this->processId = $processId;
29
-		}
30
-	}
31
-
32
-	public function __construct()
33
-	{
34
-		$this->processId = session_id();
35
-	}
36
-
37
-	public function __invoke(array $records)
38
-	{
39
-		$records['extra'] = array_merge(
40
-			$records['extra'],
41
-			[
42
-				'app_id' => $this->processId,
43
-			]
44
-		);
45
-
46
-		return $records;
47
-	}
48
-}

+ 2
- 2
src/BaseObject.php View File

@@ -6,7 +6,7 @@ namespace Friendica;
6 6
 
7 7
 require_once 'boot.php';
8 8
 
9
-use Friendica\Core\Logger;
9
+use Friendica\Util\LoggerFactory;
10 10
 
11 11
 /**
12 12
  * Basic object
@@ -27,7 +27,7 @@ class BaseObject
27 27
 	public static function getApp()
28 28
 	{
29 29
 		if (empty(self::$app)) {
30
-			$logger = Logger::create('app');
30
+			$logger = $logger = LoggerFactory::create('app');
31 31
 			self::$app = new App(dirname(__DIR__), $logger);
32 32
 		}
33 33
 

+ 5
- 6
src/Core/Addon.php View File

@@ -4,9 +4,7 @@
4 4
  */
5 5
 namespace Friendica\Core;
6 6
 
7
-use Friendica\App;
8 7
 use Friendica\BaseObject;
9
-use Friendica\Core\Logger;
10 8
 use Friendica\Database\DBA;
11 9
 
12 10
 /**
@@ -76,7 +74,7 @@ class Addon extends BaseObject
76 74
 	 */
77 75
 	public static function uninstall($addon)
78 76
 	{
79
-		Logger::log("Addons: uninstalling " . $addon);
77
+		Logger::notice("Addon {addon}: {action}", ['action' => 'uninstall', 'addon' => $addon]);
80 78
 		DBA::delete('addon', ['name' => $addon]);
81 79
 
82 80
 		@include_once('addon/' . $addon . '/' . $addon . '.php');
@@ -101,7 +99,7 @@ class Addon extends BaseObject
101 99
 		if (!file_exists('addon/' . $addon . '/' . $addon . '.php')) {
102 100
 			return false;
103 101
 		}
104
-		Logger::log("Addons: installing " . $addon);
102
+		Logger::notice("Addon {addon}: {action}", ['action' => 'install', 'addon' => $addon]);
105 103
 		$t = @filemtime('addon/' . $addon . '/' . $addon . '.php');
106 104
 		@include_once('addon/' . $addon . '/' . $addon . '.php');
107 105
 		if (function_exists($addon . '_install')) {
@@ -126,7 +124,7 @@ class Addon extends BaseObject
126 124
 			}
127 125
 			return true;
128 126
 		} else {
129
-			Logger::log("Addons: FAILED installing " . $addon);
127
+			Logger::error("Addon {addon}: {action} failed", ['action' => 'uninstall', 'addon' => $addon]);
130 128
 			return false;
131 129
 		}
132 130
 	}
@@ -156,7 +154,8 @@ class Addon extends BaseObject
156 154
 						$t = @filemtime($fname);
157 155
 						foreach ($installed as $i) {
158 156
 							if (($i['name'] == $addon) && ($i['timestamp'] != $t)) {
159
-								Logger::log('Reloading addon: ' . $i['name']);
157
+
158
+								Logger::notice("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $i['name']]);
160 159
 								@include_once($fname);
161 160
 
162 161
 								if (function_exists($addon . '_uninstall')) {

+ 291
- 128
src/Core/Logger.php View File

@@ -4,10 +4,11 @@
4 4
  */
5 5
 namespace Friendica\Core;
6 6
 
7
-use Friendica\App;
8 7
 use Friendica\BaseObject;
9
-use Monolog;
10
-use Friendica\Util\DateTimeFormat;
8
+use Friendica\Network\HTTPException\InternalServerErrorException;
9
+use Friendica\Util\LoggerFactory;
10
+use Psr\Log\LoggerInterface;
11
+use Psr\Log\LogLevel;
11 12
 
12 13
 /**
13 14
  * @brief Logger functions
@@ -15,70 +16,298 @@ use Friendica\Util\DateTimeFormat;
15 16
 class Logger extends BaseObject
16 17
 {
17 18
 	/**
18
-	 * Creates a basic Monolog instance for logging.
19
+	 * @deprecated 2019.03 use Logger::error() instead
20
+	 * @see Logger::error()
21
+	 */
22
+	const WARNING = 0;
23
+	/**
24
+	 * @deprecated 2019.03 use Logger::warning() instead
25
+	 * @see Logger::warning()
26
+	 */
27
+	const INFO = 1;
28
+	/**
29
+	 * @deprecated 2019.03 use Logger::notice() instead
30
+	 * @see Logger::notice()
31
+	 */
32
+	const TRACE = 2;
33
+	/**
34
+	 * @deprecated 2019.03 use Logger::info() instead
35
+	 * @see Logger::info()
36
+	 */
37
+	const DEBUG = 3;
38
+	/**
39
+	 * @deprecated 2019.03 use Logger::debug() instead
40
+	 * @see Logger::debug()
41
+	 */
42
+	const DATA = 4;
43
+	/**
44
+	 * @deprecated 2019.03 use Logger::debug() instead
45
+	 * @see Logger::debug()
46
+	 */
47
+	const ALL = 5;
48
+
49
+	/**
50
+	 * @var array the legacy loglevels
51
+	 * @deprecated 2019.03 use PSR-3 loglevels
52
+	 * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
19 53
 	 *
20
-	 * @param string $application the current application name (index, daemon, ...)
54
+	 */
55
+	public static $levels = [
56
+		self::WARNING => 'Warning',
57
+		self::INFO => 'Info',
58
+		self::TRACE => 'Trace',
59
+		self::DEBUG => 'Debug',
60
+		self::DATA => 'Data',
61
+		self::ALL => 'All',
62
+	];
63
+
64
+	/**
65
+	 * @var LoggerInterface A PSR-3 compliant logger instance
66
+	 */
67
+	private static $logger;
68
+
69
+	/**
70
+	 * @var LoggerInterface A PSR-3 compliant logger instance for developing only
71
+	 */
72
+	private static $devLogger;
73
+
74
+	/**
75
+	 * Sets the default logging handler for Friendica.
76
+	 * @todo Can be combined with other handlers too if necessary, could be configurable.
77
+	 *
78
+	 * @param LoggerInterface $logger The Logger instance of this Application
21 79
 	 *
22
-	 * @return Monolog\Logger The Logger instance
80
+	 * @throws InternalServerErrorException if the logger factory is incompatible to this logger
23 81
 	 */
24
-	public static function create($application)
82
+	public static function setLogger($logger)
25 83
 	{
26
-		$logger = new Monolog\Logger($application);
84
+		$debugging = Config::get('system', 'debugging');
85
+		$logfile = Config::get('system', 'logfile');
86
+		$loglevel = intval(Config::get('system', 'loglevel'));
27 87
 
28
-		$logger->pushProcessor(new Monolog\Processor\IntrospectionProcessor());
29
-		$logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
30
-		$logger->pushProcessor(new Monolog\Processor\WebProcessor());
31
-		$logger->pushProcessor(new App\FriendicaLoggerProcessor());
88
+		if (!$debugging || !$logfile) {
89
+			return;
90
+		}
91
+
92
+		LoggerFactory::addStreamHandler($logger, $logfile, $loglevel);
93
+
94
+		$logfile = Config::get('system', 'dlogfile');
95
+
96
+		if (!$logfile) {
97
+			return;
98
+		}
32 99
 
33
-		return $logger;
100
+		$developIp = Config::get('system', 'dlogip');
101
+
102
+		self::$devLogger = LoggerFactory::createDev('develop', $developIp);
103
+		LoggerFactory::addStreamHandler(self::$devLogger, $logfile, LogLevel::DEBUG);
34 104
 	}
35 105
 
36 106
 	/**
37
-	 * Sets the default Logging handler for this instance.
38
-	 * Can be combined with other handlers too if necessary.
107
+	 * System is unusable.
108
+	 * @see LoggerInterface::emergency()
109
+	 *
110
+	 * @param string $message
111
+	 * @param array  $context
112
+	 *
113
+	 * @return void
39 114
 	 *
40
-	 * @param Monolog\Logger $logger The Logger instance of this Application
41
-	 * @param App            $app    The Friendica Application
42 115
 	 */
43
-	public static function loadDefaultHandler($logger, $app)
116
+	public static function emergency($message, $context = [])
44 117
 	{
45
-		foreach ($logger->getProcessors() as $processor) {
46
-			if ($processor instanceof App\FriendicaLoggerProcessor) {
47
-				$processor->setProcessId($app->process_id);
48
-			}
118
+		if (!isset(self::$logger)) {
119
+			return;
49 120
 		}
50 121
 
51
-		$debugging = Config::get('system', 'debugging');
52
-		$logfile   = Config::get('system', 'logfile');
53
-		$loglevel = intval(Config::get('system', 'loglevel'));
122
+		$stamp1 = microtime(true);
123
+		self::$logger->emergency($message, $context);
124
+		self::getApp()->saveTimestamp($stamp1, 'file');
125
+	}
54 126
 
55
-		if (!$debugging || !$logfile) {
127
+	/**
128
+	 * Action must be taken immediately.
129
+	 * @see LoggerInterface::alert()
130
+	 *
131
+	 * Example: Entire website down, database unavailable, etc. This should
132
+	 * trigger the SMS alerts and wake you up.
133
+	 *
134
+	 * @param string $message
135
+	 * @param array  $context
136
+	 *
137
+	 * @return void
138
+	 *
139
+	 */
140
+	public static function alert($message, $context = [])
141
+	{
142
+		if (!isset(self::$logger)) {
143
+			return;
144
+		}
145
+
146
+		$stamp1 = microtime(true);
147
+		self::$logger->alert($message, $context);
148
+		self::getApp()->saveTimestamp($stamp1, 'file');
149
+	}
150
+
151
+	/**
152
+	 * Critical conditions.
153
+	 * @see LoggerInterface::critical()
154
+	 *
155
+	 * Example: Application component unavailable, unexpected exception.
156
+	 *
157
+	 * @param string $message
158
+	 * @param array  $context
159
+	 *
160
+	 * @return void
161
+	 *
162
+	 */
163
+	public static function critical($message, $context = [])
164
+	{
165
+		if (!isset(self::$logger)) {
56 166
 			return;
57 167
 		}
58 168
 
59
-		$fileHandler = new Monolog\Handler\StreamHandler($logfile . ".1", $loglevel);
60
-		$logger->pushHandler($fileHandler);
169
+		$stamp1 = microtime(true);
170
+		self::$logger->critical($message, $context);
171
+		self::getApp()->saveTimestamp($stamp1, 'file');
61 172
 	}
62 173
 
63
-    // Log levels:
64
-	//EMERGENCY
65
-	//ALERT
66
-	//CRITICAL
67
-    const WARNING = 0; //ERROR
68
-    const INFO = 1; //WARNING
69
-    const TRACE = 2; //NOTICE(default)
70
-    const DEBUG = 3; //INFO
71
-    const DATA = 4; //INFO
72
-    const ALL = 5; //DEBUG
73
-
74
-    public static $levels = [
75
-        self::WARNING => 'Warning',
76
-        self::INFO => 'Info',
77
-        self::TRACE => 'Trace',
78
-        self::DEBUG => 'Debug',
79
-        self::DATA => 'Data',
80
-        self::ALL => 'All',
81
-    ];
174
+	/**
175
+	 * Runtime errors that do not require immediate action but should typically
176
+	 * be logged and monitored.
177
+	 * @see LoggerInterface::error()
178
+	 *
179
+	 * @param string $message
180
+	 * @param array  $context
181
+	 *
182
+	 * @return void
183
+	 *
184
+	 */
185
+	public static function error($message, $context = [])
186
+	{
187
+		if (!isset(self::$logger)) {
188
+			return;
189
+		}
190
+
191
+		$stamp1 = microtime(true);
192
+		self::$logger->error($message, $context);
193
+		self::getApp()->saveTimestamp($stamp1, 'file');
194
+	}
195
+
196
+	/**
197
+	 * Exceptional occurrences that are not errors.
198
+	 * @see LoggerInterface::warning()
199
+	 *
200
+	 * Example: Use of deprecated APIs, poor use of an API, undesirable things
201
+	 * that are not necessarily wrong.
202
+	 *
203
+	 * @param string $message
204
+	 * @param array  $context
205
+	 *
206
+	 * @return void
207
+	 *
208
+	 */
209
+	public static function warning($message, $context = [])
210
+	{
211
+		if (!isset(self::$logger)) {
212
+			return;
213
+		}
214
+
215
+		$stamp1 = microtime(true);
216
+		self::$logger->warning($message, $context);
217
+		self::getApp()->saveTimestamp($stamp1, 'file');
218
+	}
219
+
220
+	/**
221
+	 * Normal but significant events.
222
+	 * @see LoggerInterface::notice()
223
+	 *
224
+	 * @param string $message
225
+	 * @param array  $context
226
+	 *
227
+	 * @return void
228
+	 *
229
+	 */
230
+	public static function notice($message, $context = [])
231
+	{
232
+		if (!isset(self::$logger)) {
233
+			return;
234
+		}
235
+
236
+		$stamp1 = microtime(true);
237
+		self::$logger->notice($message, $context);
238
+		self::getApp()->saveTimestamp($stamp1, 'file');
239
+	}
240
+
241
+	/**
242
+	 * Interesting events.
243
+	 * @see LoggerInterface::info()
244
+	 *
245
+	 * Example: User logs in, SQL logs.
246
+	 *
247
+	 * @param string $message
248
+	 * @param array  $context
249
+	 *
250
+	 * @return void
251
+	 *
252
+	 */
253
+	public static function info($message, $context = [])
254
+	{
255
+		if (!isset(self::$logger)) {
256
+			return;
257
+		}
258
+
259
+		$stamp1 = microtime(true);
260
+		self::$logger->info($message, $context);
261
+		self::getApp()->saveTimestamp($stamp1, 'file');
262
+	}
263
+
264
+	/**
265
+	 * Detailed debug information.
266
+	 * @see LoggerInterface::debug()
267
+	 *
268
+	 * @param string $message
269
+	 * @param array  $context
270
+	 *
271
+	 * @return void
272
+	 */
273
+	public static function debug($message, $context = [])
274
+	{
275
+		if (!isset(self::$logger)) {
276
+			return;
277
+		}
278
+
279
+		$stamp1 = microtime(true);
280
+		self::$logger->debug($message, $context);
281
+		self::getApp()->saveTimestamp($stamp1, 'file');
282
+	}
283
+
284
+	/**
285
+	 * Mapping a legacy level to the PSR-3 compliant levels
286
+	 * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
287
+	 *
288
+	 * @param int $level the level to be mapped
289
+	 *
290
+	 * @return string the PSR-3 compliant level
291
+	 */
292
+	private static function mapPSR3Level($level)
293
+	{
294
+		switch ($level) {
295
+			case self::WARNING:
296
+				return LogLevel::ERROR;
297
+			case self::INFO:
298
+				return LogLevel::WARNING;
299
+			case self::TRACE:
300
+				return LogLevel::NOTICE;
301
+			case self::DEBUG:
302
+				return LogLevel::INFO;
303
+			case self::DATA:
304
+				return LogLevel::DEBUG;
305
+			case self::ALL:
306
+				return LogLevel::DEBUG;
307
+			default:
308
+				return LogLevel::CRITICAL;
309
+		}
310
+	}
82 311
 
83 312
     /**
84 313
      * @brief Logs the given message at the given log level
@@ -86,52 +315,19 @@ class Logger extends BaseObject
86 315
      * @param string $msg
87 316
      * @param int $level
88 317
 	 *
89
-	 * @deprecated since 2019.03 - use App->getLogger() instead
318
+	 * @deprecated since 2019.03 Use Logger::debug() Logger::info() , ... instead
90 319
      */
91 320
     public static function log($msg, $level = self::INFO)
92 321
     {
93
-        $a = self::getApp();
94
-
95
-        $debugging = Config::get('system', 'debugging');
96
-        $logfile   = Config::get('system', 'logfile');
97
-        $loglevel = intval(Config::get('system', 'loglevel'));
98
-
99
-        if (
100
-            !$debugging
101
-            || !$logfile
102
-            || $level > $loglevel
103
-        ) {
104
-            return;
105
-        }
106
-
107
-        $processId = session_id();
108
-
109
-        if ($processId == '')
110
-        {
111
-            $processId = $a->process_id;
112
-        }
113
-
114
-        $callers = debug_backtrace();
115
-
116
-        if (count($callers) > 1) {
117
-            $function = $callers[1]['function'];
118
-        } else {
119
-            $function = '';
120
-        }
121
-
122
-        $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
123
-                DateTimeFormat::utcNow(DateTimeFormat::ATOM),
124
-                $processId,
125
-                self::$levels[$level],
126
-                basename($callers[0]['file']),
127
-                $callers[0]['line'],
128
-                $function,
129
-                $msg
130
-            );
322
+		if (!isset(self::$logger)) {
323
+			return;
324
+		}
325
+
326
+		$loglevel = self::mapPSR3Level($level);
131 327
 
132 328
         $stamp1 = microtime(true);
133
-        @file_put_contents($logfile, $logline, FILE_APPEND);
134
-        $a->saveTimestamp($stamp1, "file");
329
+		self::$logger->log($loglevel, $msg);
330
+        self::getApp()->saveTimestamp($stamp1, "file");
135 331
     }
136 332
 
137 333
     /**
@@ -141,49 +337,16 @@ class Logger extends BaseObject
141 337
      * personally without background noise
142 338
      *
143 339
      * @param string $msg
144
-	 *
145
-	 * * @deprecated since 2019.03 - never used
340
+	 * @param string $level
146 341
      */
147
-    public static function devLog($msg)
342
+    public static function devLog($msg, $level = LogLevel::DEBUG)
148 343
     {
149
-        $a = self::getApp();
150
-
151
-        $logfile = Config::get('system', 'dlogfile');
152
-
153
-        if (!$logfile) {
154
-            return;
155
-        }
156
-
157
-        $dlogip = Config::get('system', 'dlogip');
158
-
159
-        if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip)
160
-        {
161
-            return;
162
-        }
163
-
164
-        $processId = session_id();
165
-
166
-        if ($processId == '')
167
-        {
168
-            $processId = $a->process_id;
169
-        }
170
-
171
-        if (!is_string($msg)) {
172
-        	$msg = var_export($msg, true);
173
-        }
174
-
175
-        $callers = debug_backtrace();
176
-        $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
177
-                DateTimeFormat::utcNow(),
178
-                $processId,
179
-                basename($callers[0]['file']),
180
-                $callers[0]['line'],
181
-                $callers[1]['function'],
182
-                $msg
183
-            );
344
+		if (!isset(self::$logger)) {
345
+			return;
346
+		}
184 347
 
185 348
         $stamp1 = microtime(true);
186
-        @file_put_contents($logfile, $logline, FILE_APPEND);
187
-        $a->saveTimestamp($stamp1, "file");
349
+        self::$devLogger->log($level, $msg);
350
+        self::getApp()->saveTimestamp($stamp1, "file");
188 351
     }
189 352
 }

+ 50
- 0
src/Util/Logger/FriendicaDevelopHandler.php View File

@@ -0,0 +1,50 @@
1
+<?php
2
+
3
+namespace Friendica\Util\Logger;
4
+
5
+use Monolog\Handler;
6
+use Monolog\Logger;
7
+
8
+/**
9
+ * Simple handler for Friendica developers to use for deeper logging
10
+ *
11
+ * If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
12
+ * you'll use Logger::develop() for the duration of your work, and you clean it up when you're done before submitting your PR.
13
+ */
14
+class FriendicaDevelopHandler extends Handler\AbstractHandler
15
+{
16
+	/**
17
+	 * @var string The IP of the developer who wants to debug
18
+	 */
19
+	private $developerIp;
20
+
21
+	/**
22
+	 * @param string $developerIp  The IP of the developer who wants to debug
23
+	 * @param int    $level        The minimum logging level at which this handler will be triggered
24
+	 * @param bool   $bubble       Whether the messages that are handled can bubble up the stack or not
25
+	 */
26
+	public function __construct($developerIp, $level = Logger::DEBUG, $bubble = true)
27
+	{
28
+		parent::__construct($level, $bubble);
29
+
30
+		$this->developerIp = $developerIp;
31
+	}
32
+
33
+	/**
34
+	 * {@inheritdoc}
35
+	 */
36
+	public function handle(array $record)
37
+	{
38
+		if (!$this->isHandling($record)) {
39
+			return false;
40
+		}
41
+
42
+		/// Just in case the remote IP is the same as the developer IP log the output
43
+		if (!is_null($this->developerIp) && $_SERVER['REMOTE_ADDR'] != $this->developerIp)
44
+		{
45
+			return false;
46
+		}
47
+
48
+		return false === $this->bubble;
49
+	}
50
+}

+ 81
- 0
src/Util/LoggerFactory.php View File

@@ -0,0 +1,81 @@
1
+<?php
2
+
3
+namespace Friendica\Util;
4
+
5
+use Friendica\Network\HTTPException\InternalServerErrorException;
6
+use Friendica\Util\Logger\FriendicaDevelopHandler;
7
+use Monolog;
8
+use Psr\Log\LoggerInterface;
9
+use Psr\Log\LogLevel;
10
+
11
+/**
12
+ * A logger factory
13
+ *
14
+ * Currently only Monolog is supported
15
+ */
16
+class LoggerFactory
17
+{
18
+	/**
19
+	 * Creates a new PSR-3 compliant logger instances
20
+	 *
21
+	 * @param string $channel The channel of the logger instance
22
+	 *
23
+	 * @return LoggerInterface The PSR-3 compliant logger instance
24
+	 */
25
+	public static function create($channel)
26
+	{
27
+		$logger = new Monolog\Logger($channel);
28
+		$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
29
+
30
+		return $logger;
31
+	}
32
+
33
+	/**
34
+	 * Creates a new PSR-3 compliant develop logger
35
+	 *
36
+	 * If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
37
+	 * you'll use this logger instance for the duration of your work.
38
+	 *
39
+	 * It should never get filled during normal usage of Friendica
40
+	 *
41
+	 * @param string $channel      The channel of the logger instance
42
+	 * @param string $developerIp  The IP of the developer who wants to use the logger
43
+	 *
44
+	 * @return LoggerInterface The PSR-3 compliant logger instance
45
+	 */
46
+	public static function createDev($channel, $developerIp)
47
+	{
48
+		$logger = new Monolog\Logger($channel);
49
+		$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
50
+
51
+		$logger->pushHandler(new FriendicaDevelopHandler($developerIp));
52
+
53
+		return $logger;
54
+	}
55
+
56
+	/**
57
+	 * Adding a handler to a given logger instance
58
+	 *
59
+	 * @param LoggerInterface $logger  The logger instance
60
+	 * @param mixed           $stream  The stream which handles the logger output
61
+	 * @param string          $level   The level, for which this handler at least should handle logging
62
+	 *
63
+	 * @return void
64
+	 *
65
+	 * @throws InternalServerErrorException if the logger is incompatible to the logger factory
66
+	 * @throws \Exception in case of general failures
67
+	 */
68
+	public static function addStreamHandler($logger, $stream, $level = LogLevel::NOTICE)
69
+	{
70
+		if ($logger instanceof Monolog\Logger) {
71
+			$fileHandler = new Monolog\Handler\StreamHandler($stream . ".1", Monolog\Logger::toMonologLevel($level));
72
+
73
+			$formatter = new Monolog\Formatter\LineFormatter("%channel% [%level_name%]: %message% %context% %extra%");
74
+			$fileHandler->setFormatter($formatter);
75
+
76
+			$logger->pushHandler($fileHandler);
77
+		} else {
78
+			throw new InternalServerErrorException('Logger instance incompatible for MonologFactory');
79
+		}
80
+	}
81
+}

+ 2
- 2
tests/src/BaseObjectTest.php View File

@@ -7,7 +7,7 @@ namespace Friendica\Test;
7 7
 
8 8
 use Friendica\App;
9 9
 use Friendica\BaseObject;
10
-use Friendica\Core\Logger;
10
+use Friendica\Util\Logger;
11 11
 use PHPUnit\Framework\TestCase;
12 12
 
13 13
 /**
@@ -39,7 +39,7 @@ class BaseObjectTest extends TestCase
39 39
 	 */
40 40
 	public function testSetApp()
41 41
 	{
42
-		$logger = Logger::create('test');
42
+		$logger = $logger = Logger\LoggerFactory::create('test');
43 43
 		$app = new App(__DIR__ . '/../../', $logger);
44 44
 		$this->assertNull($this->baseObject->setApp($app));
45 45
 		$this->assertEquals($app, $this->baseObject->getApp());

+ 3
- 7
update.php View File

@@ -1,9 +1,9 @@
1 1
 <?php
2 2
 
3 3
 use Friendica\Core\Addon;
4
-use Friendica\BaseObject;
5 4
 use Friendica\Core\Config;
6 5
 use Friendica\Core\L10n;
6
+use Friendica\Core\Logger;
7 7
 use Friendica\Core\PConfig;
8 8
 use Friendica\Core\Update;
9 9
 use Friendica\Core\Worker;
@@ -332,9 +332,7 @@ function update_1298()
332 332
 					$fail++;
333 333
 				} else {
334 334
 					DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]);
335
-					BaseObject::getApp()
336
-						->getLogger()
337
-						->notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key,
335
+					Logger::notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key,
338 336
 						'was' => $data[$translateKey]]);
339 337
 					Worker::add(PRIORITY_LOW, 'ProfileUpdate', $data['id']);		
340 338
 					Contact::updateSelfFromUserID($data['id']);
@@ -344,9 +342,7 @@ function update_1298()
344 342
 			}
345 343
 		}
346 344
 
347
-		BaseObject::getApp()
348
-			->getLogger()
349
-			->notice($translateKey . " fix completed", ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]);
345
+		Logger::notice($translateKey . " fix completed", ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]);
350 346
 	}
351 347
 	return Update::SUCCESS;
352 348
 }

Loading…
Cancel
Save