Browse Source

Add Monolog

tags/2019.03^2
Philipp Holzer 8 months ago
parent
commit
fe8f0e0045
15 changed files with 363 additions and 121 deletions
  1. 4
    1
      bin/auth_ejabberd.php
  2. 5
    1
      bin/console.php
  3. 9
    7
      bin/daemon.php
  4. 4
    1
      bin/worker.php
  5. 2
    1
      composer.json
  6. 138
    57
      composer.lock
  7. 40
    35
      include/api.php
  8. 6
    2
      index.php
  9. 1
    1
      mod/acl.php
  10. 28
    1
      src/App.php
  11. 48
    0
      src/App/FriendicaLoggerProcessor.php
  12. 6
    1
      src/BaseObject.php
  13. 61
    8
      src/Core/Logger.php
  14. 3
    1
      tests/src/BaseObjectTest.php
  15. 8
    4
      update.php

+ 4
- 1
bin/auth_ejabberd.php View File

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

+ 5
- 1
bin/console.php View File

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

+ 9
- 7
bin/daemon.php View File

@@ -32,7 +32,9 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
32 32
 
33 33
 require dirname(__DIR__) . '/vendor/autoload.php';
34 34
 
35
-$a = new App(dirname(__DIR__));
35
+$logger = Logger::create('daemon');
36
+
37
+$a = new App(dirname(__DIR__), $logger);
36 38
 
37 39
 if ($a->getMode()->isInstall()) {
38 40
 	die("Friendica isn't properly installed yet.\n");
@@ -102,7 +104,7 @@ if ($mode == "stop") {
102 104
 
103 105
 	unlink($pidfile);
104 106
 
105
-	Logger::log("Worker daemon process $pid was killed.", Logger::DEBUG);
107
+	$logger->notice("Worker daemon process was killed", ["pid" => $pid]);
106 108
 
107 109
 	Config::set('system', 'worker_daemon_mode', false);
108 110
 	die("Worker daemon process $pid was killed.\n");
@@ -112,7 +114,7 @@ if (!empty($pid) && posix_kill($pid, 0)) {
112 114
 	die("Daemon process $pid is already running.\n");
113 115
 }
114 116
 
115
-Logger::log('Starting worker daemon.', Logger::DEBUG);
117
+$logger->notice('Starting worker daemon.', ["pid" => $pid]);
116 118
 
117 119
 if (!$foreground) {
118 120
 	echo "Starting worker daemon.\n";
@@ -160,7 +162,7 @@ $last_cron = 0;
160 162
 // Now running as a daemon.
161 163
 while (true) {
162 164
 	if (!$do_cron && ($last_cron + $wait_interval) < time()) {
163
-		Logger::log('Forcing cron worker call.', Logger::DEBUG);
165
+		$logger->info('Forcing cron worker call.', ["pid" => $pid]);
164 166
 		$do_cron = true;
165 167
 	}
166 168
 
@@ -174,7 +176,7 @@ while (true) {
174 176
 		$last_cron = time();
175 177
 	}
176 178
 
177
-	Logger::log("Sleeping", Logger::DEBUG);
179
+	$logger->info("Sleeping", ["pid" => $pid]);
178 180
 	$start = time();
179 181
 	do {
180 182
 		$seconds = (time() - $start);
@@ -191,10 +193,10 @@ while (true) {
191 193
 
192 194
 	if ($timeout) {
193 195
 		$do_cron = true;
194
-		Logger::log("Woke up after $wait_interval seconds.", Logger::DEBUG);
196
+		$logger->info("Woke up after $wait_interval seconds.", ["pid" => $pid, 'sleep' => $wait_interval]);
195 197
 	} else {
196 198
 		$do_cron = false;
197
-		Logger::log("Worker jobs are calling to be forked.", Logger::DEBUG);
199
+		$logger->info("Worker jobs are calling to be forked.", ["pid" => $pid]);
198 200
 	}
199 201
 }
200 202
 

+ 4
- 1
bin/worker.php View File

@@ -6,6 +6,7 @@
6 6
  */
7 7
 use Friendica\App;
8 8
 use Friendica\Core\Config;
9
+use Friendica\Core\Logger;
9 10
 use Friendica\Core\Worker;
10 11
 use Friendica\Core\Update;
11 12
 
@@ -28,7 +29,9 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
28 29
 
29 30
 require dirname(__DIR__) . '/vendor/autoload.php';
30 31
 
31
-$a = new App(dirname(__DIR__));
32
+$logger = Logger::create('worker');
33
+
34
+$a = new App(dirname(__DIR__), $logger);
32 35
 
33 36
 // Check the database structure and possibly fixes it
34 37
 Update::check(true);

+ 2
- 1
composer.json View File

@@ -42,7 +42,8 @@
42 42
 		"npm-asset/jgrowl": "^1.4",
43 43
 		"npm-asset/fullcalendar": "^3.0.1",
44 44
 		"npm-asset/cropperjs": "1.2.2",
45
-		"npm-asset/imagesloaded": "4.1.4"
45
+		"npm-asset/imagesloaded": "4.1.4",
46
+		"monolog/monolog": "^1.24"
46 47
 	},
47 48
 	"repositories": [
48 49
 		{

+ 138
- 57
composer.lock View File

@@ -4,7 +4,7 @@
4 4
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 5
         "This file is @generated automatically"
6 6
     ],
7
-    "content-hash": "51f7b3ab622038d7ef62ed03c06b48d0",
7
+    "content-hash": "8cf7268fbcae8a22a518b9e7727eab84",
8 8
     "packages": [
9 9
         {
10 10
             "name": "asika/simple-console",
@@ -809,6 +809,84 @@
809 809
             ],
810 810
             "time": "2018-09-01T15:05:15+00:00"
811 811
         },
812
+        {
813
+            "name": "monolog/monolog",
814
+            "version": "1.24.0",
815
+            "source": {
816
+                "type": "git",
817
+                "url": "https://github.com/Seldaek/monolog.git",
818
+                "reference": "bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266"
819
+            },
820
+            "dist": {
821
+                "type": "zip",
822
+                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266",
823
+                "reference": "bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266",
824
+                "shasum": ""
825
+            },
826
+            "require": {
827
+                "php": ">=5.3.0",
828
+                "psr/log": "~1.0"
829
+            },
830
+            "provide": {
831
+                "psr/log-implementation": "1.0.0"
832
+            },
833
+            "require-dev": {
834
+                "aws/aws-sdk-php": "^2.4.9 || ^3.0",
835
+                "doctrine/couchdb": "~1.0@dev",
836
+                "graylog2/gelf-php": "~1.0",
837
+                "jakub-onderka/php-parallel-lint": "0.9",
838
+                "php-amqplib/php-amqplib": "~2.4",
839
+                "php-console/php-console": "^3.1.3",
840
+                "phpunit/phpunit": "~4.5",
841
+                "phpunit/phpunit-mock-objects": "2.3.0",
842
+                "ruflin/elastica": ">=0.90 <3.0",
843
+                "sentry/sentry": "^0.13",
844
+                "swiftmailer/swiftmailer": "^5.3|^6.0"
845
+            },
846
+            "suggest": {
847
+                "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
848
+                "doctrine/couchdb": "Allow sending log messages to a CouchDB server",
849
+                "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
850
+                "ext-mongo": "Allow sending log messages to a MongoDB server",
851
+                "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
852
+                "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver",
853
+                "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
854
+                "php-console/php-console": "Allow sending log messages to Google Chrome",
855
+                "rollbar/rollbar": "Allow sending log messages to Rollbar",
856
+                "ruflin/elastica": "Allow sending log messages to an Elastic Search server",
857
+                "sentry/sentry": "Allow sending log messages to a Sentry server"
858
+            },
859
+            "type": "library",
860
+            "extra": {
861
+                "branch-alias": {
862
+                    "dev-master": "2.0.x-dev"
863
+                }
864
+            },
865
+            "autoload": {
866
+                "psr-4": {
867
+                    "Monolog\\": "src/Monolog"
868
+                }
869
+            },
870
+            "notification-url": "https://packagist.org/downloads/",
871
+            "license": [
872
+                "MIT"
873
+            ],
874
+            "authors": [
875
+                {
876
+                    "name": "Jordi Boggiano",
877
+                    "email": "j.boggiano@seld.be",
878
+                    "homepage": "http://seld.be"
879
+                }
880
+            ],
881
+            "description": "Sends your logs to files, sockets, inboxes, databases and various web services",
882
+            "homepage": "http://github.com/Seldaek/monolog",
883
+            "keywords": [
884
+                "log",
885
+                "logging",
886
+                "psr-3"
887
+            ],
888
+            "time": "2018-11-05T09:00:11+00:00"
889
+        },
812 890
         {
813 891
             "name": "npm-asset/cropperjs",
814 892
             "version": "1.2.2",
@@ -1019,22 +1097,6 @@
1019 1097
             "require": {
1020 1098
                 "npm-asset/ev-emitter": ">=1.0.0,<2.0.0"
1021 1099
             },
1022
-            "require-dev": {
1023
-                "npm-asset/chalk": ">=1.1.1,<2.0.0",
1024
-                "npm-asset/cheerio": ">=0.19.0,<0.20.0",
1025
-                "npm-asset/gulp": ">=3.9.0,<4.0.0",
1026
-                "npm-asset/gulp-jshint": ">=1.11.2,<2.0.0",
1027
-                "npm-asset/gulp-json-lint": ">=0.1.0,<0.2.0",
1028
-                "npm-asset/gulp-rename": ">=1.2.2,<2.0.0",
1029
-                "npm-asset/gulp-replace": ">=0.5.4,<0.6.0",
1030
-                "npm-asset/gulp-requirejs-optimize": "dev-github:metafizzy/gulp-requirejs-optimize",
1031
-                "npm-asset/gulp-uglify": ">=1.4.2,<2.0.0",
1032
-                "npm-asset/gulp-util": ">=3.0.7,<4.0.0",
1033
-                "npm-asset/highlight.js": ">=8.9.1,<9.0.0",
1034
-                "npm-asset/marked": ">=0.3.5,<0.4.0",
1035
-                "npm-asset/minimist": ">=1.2.0,<2.0.0",
1036
-                "npm-asset/transfob": ">=1.0.0,<2.0.0"
1037
-            },
1038 1100
             "type": "npm-asset-library",
1039 1101
             "extra": {
1040 1102
                 "npm-asset-bugs": {
@@ -1080,14 +1142,6 @@
1080 1142
                 "reference": null,
1081 1143
                 "shasum": "2736e332aaee73ccf0a14a5f0066391a0a13f4a3"
1082 1144
             },
1083
-            "require-dev": {
1084
-                "npm-asset/grunt": "~0.4.2",
1085
-                "npm-asset/grunt-contrib-cssmin": "~0.9.0",
1086
-                "npm-asset/grunt-contrib-jshint": "~0.6.3",
1087
-                "npm-asset/grunt-contrib-less": "~0.11.0",
1088
-                "npm-asset/grunt-contrib-uglify": "~0.4.0",
1089
-                "npm-asset/grunt-contrib-watch": "~0.6.1"
1090
-            },
1091 1145
             "type": "npm-asset-library",
1092 1146
             "extra": {
1093 1147
                 "npm-asset-bugs": {
@@ -1121,32 +1175,6 @@
1121 1175
                 "reference": null,
1122 1176
                 "shasum": "2c89d6889b5eac522a7eea32c14521559c6cbf02"
1123 1177
             },
1124
-            "require-dev": {
1125
-                "npm-asset/commitplease": "2.0.0",
1126
-                "npm-asset/core-js": "0.9.17",
1127
-                "npm-asset/grunt": "0.4.5",
1128
-                "npm-asset/grunt-babel": "5.0.1",
1129
-                "npm-asset/grunt-cli": "0.1.13",
1130
-                "npm-asset/grunt-compare-size": "0.4.0",
1131
-                "npm-asset/grunt-contrib-jshint": "0.11.2",
1132
-                "npm-asset/grunt-contrib-uglify": "0.9.2",
1133
-                "npm-asset/grunt-contrib-watch": "0.6.1",
1134
-                "npm-asset/grunt-git-authors": "2.0.1",
1135
-                "npm-asset/grunt-jscs": "2.1.0",
1136
-                "npm-asset/grunt-jsonlint": "1.0.4",
1137
-                "npm-asset/grunt-npmcopy": "0.1.0",
1138
-                "npm-asset/gzip-js": "0.3.2",
1139
-                "npm-asset/jsdom": "5.6.1",
1140
-                "npm-asset/load-grunt-tasks": "1.0.0",
1141
-                "npm-asset/qunit-assert-step": "1.0.3",
1142
-                "npm-asset/qunitjs": "1.17.1",
1143
-                "npm-asset/requirejs": "2.1.17",
1144
-                "npm-asset/sinon": "1.10.3",
1145
-                "npm-asset/sizzle": "2.2.1",
1146
-                "npm-asset/strip-json-comments": "1.0.3",
1147
-                "npm-asset/testswarm": "1.1.0",
1148
-                "npm-asset/win-spawn": "2.0.0"
1149
-            },
1150 1178
             "type": "npm-asset-library",
1151 1179
             "extra": {
1152 1180
                 "npm-asset-bugs": {
@@ -1244,6 +1272,18 @@
1244 1272
                 "npm-asset/jquery-mousewheel": ">=3.1.13",
1245 1273
                 "npm-asset/php-date-formatter": ">=1.3.4,<2.0.0"
1246 1274
             },
1275
+            "require-dev": {
1276
+                "npm-asset/chai": ">=4.1.2,<5.0.0",
1277
+                "npm-asset/concat": "dev-github:azer/concat",
1278
+                "npm-asset/concat-cli": ">=4.0.0,<5.0.0",
1279
+                "npm-asset/karma": ">=2.0.0,<3.0.0",
1280
+                "npm-asset/karma-chai": ">=0.1.0,<0.2.0",
1281
+                "npm-asset/karma-firefox-launcher": ">=1.1.0,<2.0.0",
1282
+                "npm-asset/karma-mocha": ">=1.3.0,<2.0.0",
1283
+                "npm-asset/mocha": ">=5.0.4,<6.0.0",
1284
+                "npm-asset/uglifycss": ">=0.0.27,<0.0.28",
1285
+                "npm-asset/uglifyjs": ">=2.4.10,<3.0.0"
1286
+            },
1247 1287
             "type": "npm-asset-library",
1248 1288
             "extra": {
1249 1289
                 "npm-asset-bugs": {
@@ -1297,12 +1337,6 @@
1297 1337
                 "reference": null,
1298 1338
                 "shasum": "06f0335f16e353a695e7206bf50503cb523a6ee5"
1299 1339
             },
1300
-            "require-dev": {
1301
-                "npm-asset/grunt": "~0.4.1",
1302
-                "npm-asset/grunt-contrib-connect": "~0.5.0",
1303
-                "npm-asset/grunt-contrib-jshint": "~0.7.1",
1304
-                "npm-asset/grunt-contrib-uglify": "~0.2.7"
1305
-            },
1306 1340
             "type": "npm-asset-library",
1307 1341
             "extra": {
1308 1342
                 "npm-asset-bugs": {
@@ -1854,6 +1888,53 @@
1854 1888
             ],
1855 1889
             "time": "2016-08-06T14:39:51+00:00"
1856 1890
         },
1891
+        {
1892
+            "name": "psr/log",
1893
+            "version": "1.1.0",
1894
+            "source": {
1895
+                "type": "git",
1896
+                "url": "https://github.com/php-fig/log.git",
1897
+                "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd"
1898
+            },
1899
+            "dist": {
1900
+                "type": "zip",
1901
+                "url": "https://api.github.com/repos/php-fig/log/zipball/6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd",
1902
+                "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd",
1903
+                "shasum": ""
1904
+            },
1905
+            "require": {
1906
+                "php": ">=5.3.0"
1907
+            },
1908
+            "type": "library",
1909
+            "extra": {
1910
+                "branch-alias": {
1911
+                    "dev-master": "1.0.x-dev"
1912
+                }
1913
+            },
1914
+            "autoload": {
1915
+                "psr-4": {
1916
+                    "Psr\\Log\\": "Psr/Log/"
1917
+                }
1918
+            },
1919
+            "notification-url": "https://packagist.org/downloads/",
1920
+            "license": [
1921
+                "MIT"
1922
+            ],
1923
+            "authors": [
1924
+                {
1925
+                    "name": "PHP-FIG",
1926
+                    "homepage": "http://www.php-fig.org/"
1927
+                }
1928
+            ],
1929
+            "description": "Common interface for logging libraries",
1930
+            "homepage": "https://github.com/php-fig/log",
1931
+            "keywords": [
1932
+                "log",
1933
+                "psr",
1934
+                "psr-3"
1935
+            ],
1936
+            "time": "2018-11-20T15:27:04+00:00"
1937
+        },
1857 1938
         {
1858 1939
             "name": "seld/cli-prompt",
1859 1940
             "version": "1.0.3",

+ 40
- 35
include/api.php View File

@@ -181,7 +181,7 @@ function api_login(App $a)
181 181
 		var_dump($consumer, $token);
182 182
 		die();
183 183
 	} catch (Exception $e) {
184
-		Logger::log($e);
184
+		$a->getLogger()->warning('API login: error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
185 185
 	}
186 186
 
187 187
 	// workaround for HTTP-auth in CGI mode
@@ -195,7 +195,7 @@ function api_login(App $a)
195 195
 	}
196 196
 
197 197
 	if (empty($_SERVER['PHP_AUTH_USER'])) {
198
-		Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
198
+		$a->getLogger()->debug('API login: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
199 199
 		header('WWW-Authenticate: Basic realm="Friendica"');
200 200
 		throw new UnauthorizedException("This API requires login");
201 201
 	}
@@ -236,7 +236,7 @@ function api_login(App $a)
236 236
 	}
237 237
 
238 238
 	if (!DBA::isResult($record)) {
239
-		Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
239
+		$a->getLogger()->debug('API login: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
240 240
 		header('WWW-Authenticate: Basic realm="Friendica"');
241 241
 		//header('HTTP/1.0 401 Unauthorized');
242 242
 		//die('This api requires login');
@@ -309,33 +309,35 @@ function api_call(App $a)
309 309
 					api_login($a);
310 310
 				}
311 311
 
312
-				Logger::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
313
-				Logger::log('API parameters: ' . print_r($_REQUEST, true));
312
+				$a->getLogger()->info('API call', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
313
+				$a->getLogger()->debug('API parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
314 314
 
315 315
 				$stamp =  microtime(true);
316 316
 				$return = call_user_func($info['func'], $type);
317 317
 				$duration = (float) (microtime(true) - $stamp);
318
-				Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
318
+
319
+				$a->getLogger()->info('API call', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
319 320
 
320 321
 				if (Config::get("system", "profiler")) {
321 322
 					$duration = microtime(true)-$a->performance["start"];
322 323
 
323 324
 					/// @TODO round() really everywhere?
324
-					Logger::log(
325
-						parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
326
-							"Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
327
-							round($a->performance["database"] - $a->performance["database_write"], 3),
328
-							round($a->performance["database_write"], 3),
329
-							round($a->performance["cache"], 3),
330
-							round($a->performance["cache_write"], 3),
331
-							round($a->performance["network"], 2),
332
-							round($a->performance["file"], 2),
333
-							round($duration - ($a->performance["database"]
334
-								+ $a->performance["cache"] + $a->performance["cache_write"]
335
-								+ $a->performance["network"] + $a->performance["file"]), 2),
336
-							round($duration, 2)
337
-						),
338
-						Logger::DEBUG
325
+					$a->getLogger()->debug(
326
+						'API call performance',
327
+						[
328
+							'module' => 'api',
329
+							'action' => 'performance',
330
+							'database_read' => round($a->performance["database"] - $a->performance["database_write"], 3),
331
+							'database_write' => round($a->performance["database_write"], 3),
332
+							'cache_read' => round($a->performance["cache"], 3),
333
+							'cache_write' => round($a->performance["cache_write"], 3),
334
+							'network_io' => round($a->performance["network"], 2),
335
+							'file_io' => round($a->performance["file"], 2),
336
+							'other_io' => round($duration - ($a->performance["database"]
337
+									+ $a->performance["cache"] + $a->performance["cache_write"]
338
+									+ $a->performance["network"] + $a->performance["file"]), 2),
339
+							'total' => round($duration, 2)
340
+						]
339 341
 					);
340 342
 
341 343
 					if (Config::get("rendertime", "callstack")) {
@@ -376,7 +378,7 @@ function api_call(App $a)
376 378
 								$o .= $func . ": " . $time . "\n";
377 379
 							}
378 380
 						}
379
-						Logger::log($o, Logger::DEBUG);
381
+						$a->getLogger()->debug($o, ['module' => 'api', 'action' => 'performance']);
380 382
 					}
381 383
 				}
382 384
 
@@ -413,7 +415,7 @@ function api_call(App $a)
413 415
 			}
414 416
 		}
415 417
 
416
-		Logger::log('API call not implemented: ' . $a->query_string);
418
+		$a->getLogger()->warning('API call not implemented');
417 419
 		throw new NotImplementedException();
418 420
 	} catch (HTTPException $e) {
419 421
 		header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
@@ -522,7 +524,7 @@ function api_get_user(App $a, $contact_id = null)
522 524
 	$extra_query = "";
523 525
 	$url = "";
524 526
 
525
-	Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
527
+	$a->getLogger()->info('api_get_user: Fetching user data', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
526 528
 
527 529
 	// Searching for contact URL
528 530
 	if (!is_null($contact_id) && (intval($contact_id) == 0)) {
@@ -606,7 +608,7 @@ function api_get_user(App $a, $contact_id = null)
606 608
 		}
607 609
 	}
608 610
 
609
-	Logger::log("api_get_user: user ".$user, Logger::DEBUG);
611
+	$a->getLogger()->info('api_get_user: getting user', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
610 612
 
611 613
 	if (!$user) {
612 614
 		if (api_user() === false) {
@@ -618,7 +620,7 @@ function api_get_user(App $a, $contact_id = null)
618 620
 		}
619 621
 	}
620 622
 
621
-	Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
623
+	$a->getLogger()->info('api_get_user: found user', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
622 624
 
623 625
 	// user info
624 626
 	$uinfo = q(
@@ -1937,7 +1939,7 @@ function api_conversation_show($type)
1937 1939
 		$id = intval(defaults($a->argv, 4, 0));
1938 1940
 	}
1939 1941
 
1940
-	Logger::log('API: api_conversation_show: '.$id);
1942
+	$a->getLogger()->info('API: api_conversation_show', ['module' => 'api', 'action' => 'conversation', 'id' => $id]);
1941 1943
 
1942 1944
 	// try to fetch the item for the local user - or the public item, if there is no local one
1943 1945
 	$item = Item::selectFirst(['parent-uri'], ['id' => $id]);
@@ -2331,7 +2333,7 @@ function api_favorites($type)
2331 2333
 
2332 2334
 	// in friendica starred item are private
2333 2335
 	// return favorites only for self
2334
-	Logger::log('api_favorites: self:' . $user_info['self']);
2336
+	$a->getLogger()->info('API: api_favorites', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2335 2337
 
2336 2338
 	if ($user_info['self'] == 0) {
2337 2339
 		$ret = [];
@@ -3686,6 +3688,7 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy',
3686 3688
 function api_friendships_destroy($type)
3687 3689
 {
3688 3690
 	$uid = api_user();
3691
+	$a = get_app();
3689 3692
 
3690 3693
 	if ($uid === false) {
3691 3694
 		throw new ForbiddenException();
@@ -3694,7 +3697,7 @@ function api_friendships_destroy($type)
3694 3697
 	$contact_id = defaults($_REQUEST, 'user_id');
3695 3698
 
3696 3699
 	if (empty($contact_id)) {
3697
-		Logger::log("No user_id specified", Logger::DEBUG);
3700
+		$a->getLogger()->notice('No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3698 3701
 		throw new BadRequestException("no user_id specified");
3699 3702
 	}
3700 3703
 
@@ -3702,7 +3705,7 @@ function api_friendships_destroy($type)
3702 3705
 	$contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3703 3706
 
3704 3707
 	if(!DBA::isResult($contact)) {
3705
-		Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3708
+		$a->getLogger()->notice('No contact found for ID', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3706 3709
 		throw new NotFoundException("no contact found to given ID");
3707 3710
 	}
3708 3711
 
@@ -3714,12 +3717,12 @@ function api_friendships_destroy($type)
3714 3717
 	$contact = DBA::selectFirst('contact', [], $condition);
3715 3718
 
3716 3719
 	if (!DBA::isResult($contact)) {
3717
-		Logger::log("Not following Contact", Logger::DEBUG);
3720
+		$a->getLogger()->notice('Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3718 3721
 		throw new NotFoundException("Not following Contact");
3719 3722
 	}
3720 3723
 
3721 3724
 	if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3722
-		Logger::log("Not supported", Logger::DEBUG);
3725
+		$a->getLogger()->notice('Not supported', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3723 3726
 		throw new ExpectationFailedException("Not supported");
3724 3727
 	}
3725 3728
 
@@ -3730,7 +3733,7 @@ function api_friendships_destroy($type)
3730 3733
 		Contact::terminateFriendship($owner, $contact, $dissolve);
3731 3734
 	}
3732 3735
 	else {
3733
-		Logger::log("No owner found", Logger::DEBUG);
3736
+		$a->getLogger()->notice('No owner found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3734 3737
 		throw new NotFoundException("Error Processing Request");
3735 3738
 	}
3736 3739
 
@@ -4837,7 +4840,8 @@ function api_friendica_remoteauth()
4837 4840
 		'sec' => $sec, 'expire' => time() + 45];
4838 4841
 	DBA::insert('profile_check', $fields);
4839 4842
 
4840
-	Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4843
+	$a = get_app();
4844
+	$a->getLogger()->info('API: friendica_remoteauth', ['module' => 'api', 'action' => 'remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4841 4845
 	$dest = ($url ? '&destination_url=' . $url : '');
4842 4846
 
4843 4847
 	System::externalRedirect(
@@ -5086,7 +5090,8 @@ function api_in_reply_to($item)
5086 5090
 		// https://github.com/friendica/friendica/issues/1010
5087 5091
 		// This is a bugfix for that.
5088 5092
 		if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5089
-			Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5093
+			$a = get_app();
5094
+			$a->getLogger()->warning('ID is similar to reply-to', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5090 5095
 			$in_reply_to['status_id'] = null;
5091 5096
 			$in_reply_to['user_id'] = null;
5092 5097
 			$in_reply_to['status_id_str'] = null;

+ 6
- 2
index.php View File

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

+ 1
- 1
mod/acl.php View File

@@ -34,7 +34,7 @@ function acl_content(App $a)
34 34
 		$search = $_REQUEST['query'];
35 35
 	}
36 36
 
37
-	Logger::log("Searching for ".$search." - type ".$type." conversation ".$conv_id, Logger::DEBUG);
37
+	$a->getLogger()->info("Searching for " . $search . " - type " . $type . " conversation " . $conv_id);
38 38
 
39 39
 	if ($search != '') {
40 40
 		$sql_extra = "AND `name` LIKE '%%" . DBA::escape($search) . "%%'";

+ 28
- 1
src/App.php View File

@@ -8,8 +8,10 @@ use Detection\MobileDetect;
8 8
 use DOMDocument;
9 9
 use DOMXPath;
10 10
 use Exception;
11
+use Friendica\Core\Logger;
11 12
 use Friendica\Database\DBA;
12 13
 use Friendica\Network\HTTPException\InternalServerErrorException;
14
+use Monolog;
13 15
 
14 16
 /**
15 17
  *
@@ -106,6 +108,11 @@ class App
106 108
 	 */
107 109
 	public $mobileDetect;
108 110
 
111
+	/**
112
+	 * @var Monolog\Logger The current logger of this App
113
+	 */
114
+	private $logger;
115
+
109 116
 	/**
110 117
 	 * Register a stylesheet file path to be included in the <head> tag of every page.
111 118
 	 * Inclusion is done in App->initHead().
@@ -147,12 +154,15 @@ class App
147 154
 	 * @brief App constructor.
148 155
 	 *
149 156
 	 * @param string $basePath  Path to the app base folder
157
+	 * @param Monolog\Logger    Logger of this application
150 158
 	 * @param bool   $isBackend Whether it is used for backend or frontend (Default true=backend)
151 159
 	 *
152 160
 	 * @throws Exception if the Basepath is not usable
153 161
 	 */
154
-	public function __construct($basePath, $isBackend = true)
162
+	public function __construct($basePath, $logger, $isBackend = true)
155 163
 	{
164
+		$this->logger = $logger;
165
+
156 166
 		if (!static::isDirectoryUsable($basePath, false)) {
157 167
 			throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
158 168
 		}
@@ -301,6 +311,21 @@ class App
301 311
 		return $this->mode;
302 312
 	}
303 313
 
314
+	/**
315
+	 * Returns the Logger of the Application
316
+	 *
317
+	 * @return Monolog\Logger The Logger
318
+	 * @throws InternalServerErrorException when the logger isn't created
319
+	 */
320
+	public function getLogger()
321
+	{
322
+		if (empty($this->logger)) {
323
+			throw new InternalServerErrorException('Logger of the Application is not defined');
324
+		}
325
+
326
+		return $this->logger;
327
+	}
328
+
304 329
 	/**
305 330
 	 * Reloads the whole app instance
306 331
 	 */
@@ -328,6 +353,8 @@ class App
328 353
 		Core\L10n::init();
329 354
 
330 355
 		$this->process_id = Core\System::processID('log');
356
+
357
+		Logger::loadDefaultHandler($this->logger, $this);
331 358
 	}
332 359
 
333 360
 	/**

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

@@ -0,0 +1,48 @@
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
+}

+ 6
- 1
src/BaseObject.php View File

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

+ 61
- 8
src/Core/Logger.php View File

@@ -4,23 +4,72 @@
4 4
  */
5 5
 namespace Friendica\Core;
6 6
 
7
+use Friendica\App;
7 8
 use Friendica\BaseObject;
8
-use Friendica\Core\Config;
9
+use Monolog;
9 10
 use Friendica\Util\DateTimeFormat;
10
-use ReflectionClass;
11 11
 
12 12
 /**
13 13
  * @brief Logger functions
14 14
  */
15 15
 class Logger extends BaseObject
16 16
 {
17
+	/**
18
+	 * Creates a basic Monolog instance for logging.
19
+	 *
20
+	 * @param string $application the current application name (index, daemon, ...)
21
+	 *
22
+	 * @return Monolog\Logger The Logger instance
23
+	 */
24
+	public static function create($application)
25
+	{
26
+		$logger = new Monolog\Logger($application);
27
+
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());
32
+
33
+		return $logger;
34
+	}
35
+
36
+	/**
37
+	 * Sets the default Logging handler for this instance.
38
+	 * Can be combined with other handlers too if necessary.
39
+	 *
40
+	 * @param Monolog\Logger $logger The Logger instance of this Application
41
+	 * @param App            $app    The Friendica Application
42
+	 */
43
+	public static function loadDefaultHandler($logger, $app)
44
+	{
45
+		foreach ($logger->getProcessors() as $processor) {
46
+			if ($processor instanceof App\FriendicaLoggerProcessor) {
47
+				$processor->setProcessId($app->process_id);
48
+			}
49
+		}
50
+
51
+		$debugging = Config::get('system', 'debugging');
52
+		$logfile   = Config::get('system', 'logfile');
53
+		$loglevel = intval(Config::get('system', 'loglevel'));
54
+
55
+		if (!$debugging || !$logfile) {
56
+			return;
57
+		}
58
+
59
+		$fileHandler = new Monolog\Handler\StreamHandler($logfile . ".1", $loglevel);
60
+		$logger->pushHandler($fileHandler);
61
+	}
62
+
17 63
     // Log levels:
18
-    const WARNING = 0;
19
-    const INFO = 1;
20
-    const TRACE = 2;
21
-    const DEBUG = 3;
22
-    const DATA = 4;
23
-    const ALL = 5;
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
24 73
 
25 74
     public static $levels = [
26 75
         self::WARNING => 'Warning',
@@ -36,6 +85,8 @@ class Logger extends BaseObject
36 85
      *
37 86
      * @param string $msg
38 87
      * @param int $level
88
+	 *
89
+	 * @deprecated since 2019.03 - use App->getLogger() instead
39 90
      */
40 91
     public static function log($msg, $level = self::INFO)
41 92
     {
@@ -90,6 +141,8 @@ class Logger extends BaseObject
90 141
      * personally without background noise
91 142
      *
92 143
      * @param string $msg
144
+	 *
145
+	 * * @deprecated since 2019.03 - never used
93 146
      */
94 147
     public static function devLog($msg)
95 148
     {

+ 3
- 1
tests/src/BaseObjectTest.php View File

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

+ 8
- 4
update.php View File

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

Loading…
Cancel
Save