From b0a87832768974c9d8b5ea8ce3bf79c0586b9ed8 Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Tue, 30 May 2023 18:12:24 +0900 Subject: [PATCH] Logging class major change, Debug\Support update old Debug\Logging is in Debug\LoggingLegacy and Debug\Logging extends Logging\Logging Logging\Logging is a new class with most of the functionality except there is no more print/outout to screen, but we use the default log levels (RFC5424) The plan is to be a frontend between the old type class and Monolog\Monolog Updated all other classes to use new class interface --- .phan/config.php | 5 +- 4dev/tests/ACL/CoreLibsACLLoginTest.php | 7 +- 4dev/tests/Create/CoreLibsCreateEmailTest.php | 13 +- 4dev/tests/DB/CoreLibsDBIOTest.php | 7 +- ...php => CoreLibsDebugLoggingLegacyTest.php} | 31 +- 4dev/tests/Debug/CoreLibsDebugSupportTest.php | 608 +++++--- .../Logging/CoreLibsLoggingLoggingTest.php | 797 ++++++++++ 4dev/tests/Logging/log/.gitignore | 3 + www/admin/class_test.admin.backend.php | 19 +- www/admin/class_test.array.php | 19 +- www/admin/class_test.autoloader.php | 5 - www/admin/class_test.byte.php | 19 +- www/admin/class_test.check.colors.php | 19 +- www/admin/class_test.config.direct.php | 19 +- www/admin/class_test.config.link.php | 19 +- www/admin/class_test.convert.colors.php | 19 +- www/admin/class_test.create_email.php | 21 +- www/admin/class_test.datetime.php | 19 +- www/admin/class_test.db.dbReturn.php | 37 +- www/admin/class_test.db.php | 20 +- www/admin/class_test.db.single.php | 20 +- www/admin/class_test.debug.php | 48 +- www/admin/class_test.email.php | 19 +- www/admin/class_test.encoding.php | 22 +- www/admin/class_test.encryption.php | 20 +- www/admin/class_test.file.php | 19 +- www/admin/class_test.hash.php | 19 +- www/admin/class_test.html.php | 19 +- www/admin/class_test.image.php | 21 +- www/admin/class_test.json.php | 19 +- www/admin/class_test.lang.php | 5 - www/admin/class_test.logging.php | 94 ++ www/admin/class_test.login.php | 19 +- www/admin/class_test.math.php | 19 +- www/admin/class_test.memoryusage.php | 19 +- www/admin/class_test.mime.php | 18 +- www/admin/class_test.output.form.php | 19 +- www/admin/class_test.password.php | 19 +- www/admin/class_test.php | 62 +- www/admin/class_test.phpv.php | 19 +- www/admin/class_test.randomkey.php | 19 +- www/admin/class_test.readenvfile.php | 14 +- www/admin/class_test.runningtime.php | 19 +- www/admin/class_test.session.php | 19 +- www/admin/class_test.session.read.php | 19 +- www/admin/class_test.smarty.php | 21 +- www/admin/class_test.strings.php | 19 +- www/admin/class_test.system.php | 19 +- www/admin/class_test.token.php | 19 +- www/admin/class_test.uids.php | 19 +- www/admin/class_test.varistype.php | 19 +- www/admin/error_test.php | 7 +- .../subfolder/class_test.config.direct.php | 19 +- www/admin/test_edit_base.php | 16 +- www/configs/config.host.php | 4 +- www/configs/config.master.php | 30 +- www/includes/admin_header.php | 27 +- www/includes/edit_base.php | 11 +- www/lib/CoreLibs/ACL/Login.php | 29 +- www/lib/CoreLibs/Admin/Backend.php | 8 +- www/lib/CoreLibs/Admin/EditBase.php | 8 +- www/lib/CoreLibs/Basic.php | 97 +- www/lib/CoreLibs/Create/Email.php | 10 +- www/lib/CoreLibs/DB/Extended/ArrayIO.php | 4 +- www/lib/CoreLibs/DB/IO.php | 12 +- www/lib/CoreLibs/Debug/Logging.php | 883 +---------- www/lib/CoreLibs/Debug/LoggingLegacy.php | 911 ++++++++++++ www/lib/CoreLibs/Debug/Support.php | 136 +- www/lib/CoreLibs/Logging/Logger/Flag.php | 107 ++ www/lib/CoreLibs/Logging/Logger/Level.php | 216 +++ www/lib/CoreLibs/Logging/Logging.php | 1319 +++++++++++++++++ www/lib/CoreLibs/Output/Form/Generate.php | 11 +- www/lib/Error.Handling.php | 9 +- www/lib/Test/DB/TestDB.php | 4 +- www/lib/Test/Test.php | 2 +- 75 files changed, 4292 insertions(+), 2019 deletions(-) rename 4dev/tests/Debug/{CoreLibsDebugLoggingTest.php => CoreLibsDebugLoggingLegacyTest.php} (96%) create mode 100644 4dev/tests/Logging/CoreLibsLoggingLoggingTest.php create mode 100644 4dev/tests/Logging/log/.gitignore create mode 100644 www/admin/class_test.logging.php create mode 100644 www/lib/CoreLibs/Debug/LoggingLegacy.php create mode 100644 www/lib/CoreLibs/Logging/Logger/Flag.php create mode 100644 www/lib/CoreLibs/Logging/Logger/Level.php create mode 100644 www/lib/CoreLibs/Logging/Logging.php diff --git a/.phan/config.php b/.phan/config.php index 73d1b51f..87257f93 100644 --- a/.phan/config.php +++ b/.phan/config.php @@ -128,7 +128,10 @@ return [ 'PhanWriteOnlyPublicProperty', 'PhanUnreferencedConstant', 'PhanWriteOnlyPublicProperty', - 'PhanReadOnlyPublicProperty' + 'PhanReadOnlyPublicProperty', + // start ignore annotations + 'PhanUnextractableAnnotationElementName', + 'PhanUnextractableAnnotationSuffix' ], // Override to hardcode existence and types of (non-builtin) globals in the global scope. diff --git a/4dev/tests/ACL/CoreLibsACLLoginTest.php b/4dev/tests/ACL/CoreLibsACLLoginTest.php index 5ca89254..60958dcf 100644 --- a/4dev/tests/ACL/CoreLibsACLLoginTest.php +++ b/4dev/tests/ACL/CoreLibsACLLoginTest.php @@ -68,13 +68,10 @@ final class CoreLibsACLLoginTest extends TestCase // logger is always needed // define basic connection set valid and one invalid - self::$log = new \CoreLibs\Debug\Logging([ + self::$log = new \CoreLibs\Logging\Logging([ // 'log_folder' => __DIR__ . DIRECTORY_SEPARATOR . 'log', 'log_folder' => DIRECTORY_SEPARATOR . 'tmp', - 'file_id' => 'CoreLibs-ACL-Login-Test', - 'debug_all' => true, - 'echo_all' => false, - 'print_all' => true, + 'log_file_id' => 'CoreLibs-ACL-Login-Test', ]); // test database we need to connect do, if not possible this test is skipped self::$db = new \CoreLibs\DB\IO( diff --git a/4dev/tests/Create/CoreLibsCreateEmailTest.php b/4dev/tests/Create/CoreLibsCreateEmailTest.php index c0301004..3d170be7 100644 --- a/4dev/tests/Create/CoreLibsCreateEmailTest.php +++ b/4dev/tests/Create/CoreLibsCreateEmailTest.php @@ -22,12 +22,9 @@ final class CoreLibsCreateEmailTest extends TestCase */ public static function setUpBeforeClass(): void { - self::$log = new \CoreLibs\Debug\Logging([ + self::$log = new \CoreLibs\Logging\Logging([ 'log_folder' => DIRECTORY_SEPARATOR . 'tmp', - 'file_id' => 'CoreLibs-Create-Email-Test', - 'debug_all' => true, - 'echo_all' => false, - 'print_all' => true, + 'log_file_id' => 'CoreLibs-Create-Email-Test', ]); } @@ -624,7 +621,7 @@ final class CoreLibsCreateEmailTest extends TestCase // force new set for each run self::$log->setLogUniqueId(true); // set on of unique log id - self::$log->setLogPer('run', true); + self::$log->setLogFlag(\CoreLibs\Logging\Logger\Flag::per_run); // init logger $status = \CoreLibs\Create\Email::sendEmail( $subject, @@ -646,7 +643,9 @@ final class CoreLibsCreateEmailTest extends TestCase // assert content: must load JSON from log file if ($status == 2) { // open file, get last entry with 'SEND EMAIL JSON' key - $file = file_get_contents(self::$log->getLogFileName()); + $file = file_get_contents( + self::$log->getLogFolder() . self::$log->getLogFile() + ); if ($file !== false) { // extract SEND EMAIL JSON line $found = preg_match_all("/^.* - (.*)$/m", $file, $matches); diff --git a/4dev/tests/DB/CoreLibsDBIOTest.php b/4dev/tests/DB/CoreLibsDBIOTest.php index 20e90fda..b60d4549 100644 --- a/4dev/tests/DB/CoreLibsDBIOTest.php +++ b/4dev/tests/DB/CoreLibsDBIOTest.php @@ -132,13 +132,10 @@ final class CoreLibsDBIOTest extends TestCase ); } // define basic connection set valid and one invalid - self::$log = new \CoreLibs\Debug\Logging([ + self::$log = new \CoreLibs\Logging\Logging([ // 'log_folder' => __DIR__ . DIRECTORY_SEPARATOR . 'log', 'log_folder' => DIRECTORY_SEPARATOR . 'tmp', - 'file_id' => 'CoreLibs-DB-IO-Test', - 'debug_all' => false, - 'echo_all' => false, - 'print_all' => false, + 'log_file_id' => 'CoreLibs-DB-IO-Test', ]); $db = new \CoreLibs\DB\IO( self::$db_config['valid'], diff --git a/4dev/tests/Debug/CoreLibsDebugLoggingTest.php b/4dev/tests/Debug/CoreLibsDebugLoggingLegacyTest.php similarity index 96% rename from 4dev/tests/Debug/CoreLibsDebugLoggingTest.php rename to 4dev/tests/Debug/CoreLibsDebugLoggingLegacyTest.php index 6b7daad0..b06c86bd 100644 --- a/4dev/tests/Debug/CoreLibsDebugLoggingTest.php +++ b/4dev/tests/Debug/CoreLibsDebugLoggingLegacyTest.php @@ -10,12 +10,13 @@ use PHPUnit\Framework\TestCase; /** * Test class for Debug\Logging - * @coversDefaultClass \CoreLibs\Debug\Logging - * @testdox \CoreLibs\Debug\Logging method tests + * @coversDefaultClass \CoreLibs\Debug\LoggingLegacy + * @testdox \CoreLibs\Debug\LoggingLegacy method tests */ -final class CoreLibsDebugLoggingTest extends TestCase +final class CoreLibsDebugLoggingLegacyTest extends TestCase { private const LOG_FOLDER = __DIR__ . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR; + /** * test set for options BASIC * @@ -24,7 +25,7 @@ final class CoreLibsDebugLoggingTest extends TestCase * 1: expected * 2: override * override: - * - constant for COSNTANTS + * - constant for CONSTANTS * - global for _GLOBALS * * @return array @@ -138,7 +139,7 @@ final class CoreLibsDebugLoggingTest extends TestCase // catch this with the message $this->expectExceptionMessage($deprecation_message); } - $log = new \CoreLibs\Debug\Logging($options); + $log = new \CoreLibs\Debug\LoggingLegacy($options); // reset error handler restore_error_handler(); // check that settings match @@ -308,7 +309,7 @@ final class CoreLibsDebugLoggingTest extends TestCase // catch this with the message $this->expectExceptionMessage($deprecation_message); } - $log = new \CoreLibs\Debug\Logging($options); + $log = new \CoreLibs\Debug\LoggingLegacy($options); // reset error handler restore_error_handler(); // check current @@ -385,7 +386,7 @@ final class CoreLibsDebugLoggingTest extends TestCase bool $expected_get ): void { // neutral start with default - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testSetGetLogLevelAll', 'log_folder' => self::LOG_FOLDER ]); @@ -510,7 +511,7 @@ final class CoreLibsDebugLoggingTest extends TestCase $expected_get ): void { // neutral start with default - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testSetGetLogLevel', 'log_folder' => self::LOG_FOLDER ]); @@ -592,7 +593,7 @@ final class CoreLibsDebugLoggingTest extends TestCase bool $expected_get ): void { // neutral start with default - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testSetGetLogPer', 'log_folder' => self::LOG_FOLDER ]); @@ -624,7 +625,7 @@ final class CoreLibsDebugLoggingTest extends TestCase public function testSetGetLogPrintFileDate(bool $input, bool $expected_set, bool $expected_get): void { // neutral start with default - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testSetGetLogPrintFileDate', 'log_folder' => self::LOG_FOLDER ]); @@ -693,7 +694,7 @@ final class CoreLibsDebugLoggingTest extends TestCase */ public function testPrAr(array $input, string $expected): void { - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testPrAr', 'log_folder' => self::LOG_FOLDER ]); @@ -757,7 +758,7 @@ final class CoreLibsDebugLoggingTest extends TestCase */ public function testPrBl(bool $input, ?string $true, ?string $false, string $expected): void { - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testPrBl', 'log_folder' => self::LOG_FOLDER ]); @@ -932,7 +933,7 @@ final class CoreLibsDebugLoggingTest extends TestCase // remove any files named /tmp/error_log_TestDebug*.log array_map('unlink', glob($options['log_folder'] . 'error_msg_' . $options['file_id'] . '*.log')); // init logger - $log = new \CoreLibs\Debug\Logging($options); + $log = new \CoreLibs\Debug\LoggingLegacy($options); // * debug (A/B) // NULL check for strip/prefix $this->assertEquals( @@ -1046,13 +1047,13 @@ final class CoreLibsDebugLoggingTest extends TestCase public function testLogUniqueId(bool $option, bool $override): void { if ($option === true) { - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testLogUniqueId', 'log_folder' => self::LOG_FOLDER, 'per_run' => $option ]); } else { - $log = new \CoreLibs\Debug\Logging([ + $log = new \CoreLibs\Debug\LoggingLegacy([ 'file_id' => 'testLogUniqueId', 'log_folder' => self::LOG_FOLDER ]); diff --git a/4dev/tests/Debug/CoreLibsDebugSupportTest.php b/4dev/tests/Debug/CoreLibsDebugSupportTest.php index e5bc52ae..f8463233 100644 --- a/4dev/tests/Debug/CoreLibsDebugSupportTest.php +++ b/4dev/tests/Debug/CoreLibsDebugSupportTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace tests; use PHPUnit\Framework\TestCase; +use CoreLibs\Debug\Support; /** * Test class for Debug\Support @@ -40,6 +41,32 @@ final class CoreLibsDebugSupportTest extends TestCase ]; } + /** + * Undocumented function + * + * @cover ::printTime + * @dataProvider printTimeProvider + * @testdox printTime test with $microtime and match to regex [$_dataName] + * + * @param int|null $mircrotime + * @param string $expected + * @return void + */ + public function testPrintTime(?int $microtime, string $regex): void + { + if ($microtime === null) { + $this->assertMatchesRegularExpression( + $regex, + Support::printTime() + ); + } else { + $this->assertMatchesRegularExpression( + $regex, + Support::printTime($microtime) + ); + } + } + /** * Undocumented function * @@ -50,18 +77,55 @@ final class CoreLibsDebugSupportTest extends TestCase return [ 'empty array' => [ 0 => [], - 1 => "
Array\n(\n)\n
" + 1 => "
Array\n(\n)\n
", + 2 => "Array\n(\n)\n", ], 'simple array' => [ 0 => ['a', 'b'], 1 => "
Array\n(\n"
 					. "    [0] => a\n"
 					. "    [1] => b\n"
-					. ")\n
" + . ")\n", + 2 => "Array\n(\n" + . " [0] => a\n" + . " [1] => b\n" + . ")\n", ], ]; } + /** + * Undocumented function + * + * @cover ::printAr + * @cover ::printArray + * @dataProvider printArrayProvider + * @testdox printAr/printArray $input will be $expected [$_dataName] + * + * @param array $input + * @param string $expected + * @param string $expected_strip + * @return void + */ + public function testPrintAr(array $input, string $expected, string $expected_strip): void + { + $this->assertEquals( + $expected, + Support::printAr($input), + 'assert printAr' + ); + $this->assertEquals( + $expected, + Support::printArray($input), + 'assert printArray' + ); + $this->assertEquals( + $expected_strip, + Support::prAr($input), + 'assert prAr' + ); + } + /** * Undocumented function * @@ -73,27 +137,31 @@ final class CoreLibsDebugSupportTest extends TestCase 'true input default' => [ 0 => true, 1 => [], - 2 => 'true' + 2 => 'true', + 3 => 'true', ], 'false input default' => [ 0 => false, 1 => [], - 2 => 'false' + 2 => 'false', + 3 => 'false' ], 'false input param name' => [ 0 => false, 1 => [ 'name' => 'param test' ], - 2 => 'param test: false' + 2 => 'param test: false', + 3 => 'false' ], 'true input param name, true override' => [ 0 => true, 1 => [ 'name' => 'param test', - 'true' => 'ok' + 'true' => 'ok', ], - 2 => 'param test: ok' + 2 => 'param test: ok', + 3 => 'ok', ], 'false input param name, true override, false override' => [ 0 => false, @@ -102,11 +170,77 @@ final class CoreLibsDebugSupportTest extends TestCase 'true' => 'ok', 'false' => 'not', ], - 2 => 'param test: not' + 2 => 'param test: not', + 3 => 'not' ], ]; } + /** + * Undocumented function + * + * @cover ::printBool + * @dataProvider printBoolProvider + * @testdox printBool $input will be $expected [$_dataName] + * + * @param bool $input + * @param array $params + * @param string $expected + * @param string $expected_strip + * @return void + */ + public function testPrintBool(bool $input, array $params, string $expected, string $expected_strip): void + { + if ( + isset($params['name']) && + isset($params['true']) && + isset($params['false']) + ) { + $string = Support::printBool( + $input, + $params['name'], + $params['true'], + $params['false'] + ); + $string_strip = Support::prBl( + $input, + $params['true'], + $params['false'] + ); + } elseif (isset($params['name']) && isset($params['true'])) { + $string = Support::printBool( + $input, + $params['name'], + $params['true'] + ); + $string_strip = Support::prBl( + $input, + $params['true'], + ); + } elseif (isset($params['name'])) { + $string = Support::printBool( + $input, + $params['name'] + ); + $string_strip = Support::prBl( + $input + ); + } else { + $string = Support::printBool($input); + $string_strip = Support::prBl($input); + } + $this->assertEquals( + $expected, + $string, + 'assert printBool' + ); + $this->assertEquals( + $expected_strip, + $string_strip, + 'assert prBl' + ); + } + /** * Undocumented function * @@ -169,12 +303,10 @@ final class CoreLibsDebugSupportTest extends TestCase 'an array, no html' => [ ['a', 'b'], true, - "##HTMLPRE##" - . "Array\n(\n" + "Array\n(\n" . " [0] => a\n" . " [1] => b\n" - . ")\n" - . "##/HTMLPRE##", + . ")\n", ], // resource 'a resource' => [ @@ -191,6 +323,253 @@ final class CoreLibsDebugSupportTest extends TestCase ]; } + /** + * Undocumented function + * + * @cover ::printToString + * @dataProvider printToStringProvider + * @testdox printToString $input with $flag will be $expected [$_dataName] + * + * @param mixed $input anything + * @param boolean|null $flag html flag, only for string and array + * @param string $expected always string + * @return void + */ + public function testPrintToString(mixed $input, ?bool $flag, string $expected): void + { + if ($flag === null) { + // if expected starts with / and ends with / then this is a regex compare + if ( + substr($expected, 0, 1) == '/' && + substr($expected, -1, 1) == '/' + ) { + $this->assertMatchesRegularExpression( + $expected, + Support::printToString($input) + ); + } else { + $this->assertEquals( + $expected, + Support::printToString($input) + ); + } + } else { + $this->assertEquals( + $expected, + Support::printToString($input, $flag) + ); + } + } + + /** + * Undocumented function + * + * @return array + */ + public function providerDumpExportVar(): array + { + return [ + 'string' => [ + 'input' => 'string', + 'flag' => null, + 'expected_dump' => 'string(6) "string"' . "\n", + 'expected_export' => "
'string'
", + ], + 'string, no html' => [ + 'input' => 'string', + 'flag' => true, + 'expected_dump' => 'string(6) "string"' . "\n", + 'expected_export' => "'string'", + ], + // int + 'int' => [ + 'input' => 6, + 'flag' => null, + 'expected_dump' => 'int(6)' . "\n", + 'expected_export' => "
6
", + ], + // float + 'float' => [ + 'input' => 1.6, + 'flag' => null, + 'expected_dump' => 'float(1.6)' . "\n", + 'expected_export' => "
1.6
", + ], + // bool + 'bool' => [ + 'input' => true, + 'flag' => null, + 'expected_dump' => 'bool(true)' . "\n", + 'expected_export' => "
true
", + ], + // array + 'array' => [ + 'input' => ['string', true], + 'flag' => null, + 'expected_dump' => "array(2) {\n" + . " [0]=>\n" + . " string(6) \"string\"\n" + . " [1]=>\n" + . " bool(true)\n" + . "}\n", + 'expected_export' => "
array (\n"
+					. "  0 => 'string',\n"
+					. "  1 => true,\n"
+					. ")
", + ], + // more + ]; + } + + /** + * Undocumented function + * + * @cover ::dumpVar + * @cover ::exportVar + * @dataProvider providerDumpExportVar + * @testdox dump/exportVar $input with $flag will be $expected_dump / $expected_export [$_dataName] + * + * @param mixed $input + * @param bool|null $flag + * @param string $expected_dump + * @param string $expected_export + * @return void + */ + public function testDumpExportVar(mixed $input, ?bool $flag, string $expected_dump, string $expected_export): void + { + if ($flag === null) { + $dump = Support::dumpVar($input); + $export = Support::exportVar($input); + } else { + $dump = Support::dumpVar($input, $flag); + $export = Support::exportVar($input, $flag); + } + $this->assertEquals( + $expected_dump, + $dump, + 'assert dumpVar' + ); + $this->assertEquals( + $expected_export, + $export, + 'assert dumpVar' + ); + } + + /** + * Undocumented function + * + * @cover ::getCallerFileLine + * @testWith ["/storage/var/www/html/developers/clemens/core_data/php_libraries/trunk/www/vendor/phpunit/phpunit/src/Framework/TestCase.php:1608"] + * @testdox getCallerFileLine check if it returns $expected [$_dataName] + * + * @param string $expected + * @return void + */ + public function testGetCallerFileLine(string $expected): void + { + $this->assertEquals( + $expected, + Support::getCallerFileLine() + ); + } + + /** + * Undocumented function + * + * @cover ::getCallerMethod + * @testWith ["testGetCallerMethod"] + * @testdox getCallerMethod check if it returns $expected [$_dataName] + * + * @return void + */ + public function testGetCallerMethod(string $expected): void + { + $this->assertEquals( + $expected, + Support::getCallerMethod() + ); + } + + /** + * Undocumented function + * + * @cover ::getCallerMethodList + * @testWith [["main", "run", "run", "run", "run", "run", "run", "runBare", "runTest", "testGetCallerMethodList"]] + * @testdox getCallerMethodList check if it returns $expected [$_dataName] + * + * @param array $expected + * @return void + */ + public function testGetCallerMethodList(array $expected): void + { + $compare = Support::getCallerMethodList(); + // 10: legact + // 11: direct + // 12: full call + switch (count($compare)) { + case 10: + // add nothing + $this->assertEquals( + $expected, + Support::getCallerMethodList(), + 'assert expected 10' + ); + break; + case 11: + // add one "run" before "runBare" + array_splice( + $expected, + 7, + 0, + ['run'] + ); + $this->assertEquals( + $expected, + Support::getCallerMethodList(), + 'assert expected 11' + ); + break; + case 12: + // add two "run" before "runBare" + array_splice( + $expected, + 7, + 0, + ['run'] + ); + array_splice( + $expected, + 0, + 0, + ['include'] + ); + $this->assertEquals( + $expected, + Support::getCallerMethodList(), + 'assert expected 12' + ); + break; + } + } + + /** + * Undocumented function + * + * @cover ::getCallerClass + * @testWith ["PHPUnit\\TextUI\\Command"] + * @testdox getCallerClass check if it returns $expected [$_dataName] + * + * @return void + */ + public function testGetCallerClass(string $expected): void + { + $this->assertEquals( + $expected, + Support::getCallerClass() + ); + } + /** * Undocumented function * @@ -236,205 +615,6 @@ final class CoreLibsDebugSupportTest extends TestCase ]; } - /** - * Undocumented function - * - * @cover ::printTime - * @dataProvider printTimeProvider - * @testdox printTime test with $microtime and match to regex [$_dataName] - * - * @param int|null $mircrotime - * @param string $expected - * @return void - */ - public function testPrintTime(?int $microtime, string $regex): void - { - if ($microtime === null) { - $this->assertMatchesRegularExpression( - $regex, - \CoreLibs\Debug\Support::printTime() - ); - } else { - $this->assertMatchesRegularExpression( - $regex, - \CoreLibs\Debug\Support::printTime($microtime) - ); - } - } - - /** - * Undocumented function - * - * @cover ::printAr - * @cover ::printArray - * @dataProvider printArrayProvider - * @testdox printAr/printArray $input will be $expected [$_dataName] - * - * @param array $input - * @param string $expected - * @return void - */ - public function testPrintAr(array $input, string $expected): void - { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::printAr($input), - 'assert printAr' - ); - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::printArray($input), - 'assert printArray' - ); - } - - /** - * Undocumented function - * - * @cover ::printBool - * @dataProvider printBoolProvider - * @testdox printBool $input will be $expected [$_dataName] - * - * @param bool $input - * @param array $params - * @param string $expected - * @return void - */ - public function testPrintBool(bool $input, array $params, string $expected): void - { - if ( - isset($params['name']) && - isset($params['true']) && - isset($params['false']) - ) { - $string = \CoreLibs\Debug\Support::printBool( - $input, - $params['name'], - $params['true'], - $params['false'] - ); - } elseif (isset($params['name']) && isset($params['true'])) { - $string = \CoreLibs\Debug\Support::printBool( - $input, - $params['name'], - $params['true'] - ); - } elseif (isset($params['name'])) { - $string = \CoreLibs\Debug\Support::printBool( - $input, - $params['name'] - ); - } else { - $string = \CoreLibs\Debug\Support::printBool($input); - } - $this->assertEquals( - $expected, - $string, - 'assert printBool' - ); - } - - /** - * Undocumented function - * - * @cover ::printToString - * @dataProvider printToStringProvider - * @testdox printToString $input with $flag will be $expected [$_dataName] - * - * @param mixed $input anything - * @param boolean|null $flag html flag, only for string and array - * @param string $expected always string - * @return void - */ - public function testPrintToString(mixed $input, ?bool $flag, string $expected): void - { - if ($flag === null) { - // if expected starts with / and ends with / then this is a regex compare - if ( - substr($expected, 0, 1) == '/' && - substr($expected, -1, 1) == '/' - ) { - $this->assertMatchesRegularExpression( - $expected, - \CoreLibs\Debug\Support::printToString($input) - ); - } else { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::printToString($input) - ); - } - } else { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::printToString($input, $flag) - ); - } - } - - /** - * Undocumented function - * - * @cover ::getCallerMethod - * @testWith ["testGetCallerMethod"] - * @testdox getCallerMethod check if it returns $expected [$_dataName] - * - * @return void - */ - public function testGetCallerMethod(string $expected): void - { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::getCallerMethod() - ); - } - - /** - * Undocumented function - * - * @cover ::getCallerMethodList - * @testWith [["main", "run", "run", "run", "run", "run", "run", "runBare", "runTest", "testGetCallerMethodList"],["include", "main", "run", "run", "run", "run", "run", "run", "run", "runBare", "runTest", "testGetCallerMethodList"]] - * @testdox getCallerMethodList check if it returns $expected [$_dataName] - * - * @param array $expected - * @return void - */ - public function testGetCallerMethodList(array $expected, array $expected_group): void - { - $compare = \CoreLibs\Debug\Support::getCallerMethodList(); - // if we direct call we have 10, if we call as folder we get 11 - if (count($compare) == 10) { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::getCallerMethodList(), - 'assert expected 10' - ); - } else { - $this->assertEquals( - $expected_group, - \CoreLibs\Debug\Support::getCallerMethodList(), - 'assert expected group' - ); - } - } - - /** - * Undocumented function - * - * @cover ::getCallerClass - * @testWith ["PHPUnit\\TextUI\\Command"] - * @testdox getCallerClass check if it returns $expected [$_dataName] - * - * @return void - */ - public function testGetCallerClass(string $expected): void - { - $this->assertEquals( - $expected, - \CoreLibs\Debug\Support::getCallerClass() - ); - } - /** * Undocumented function * @@ -453,19 +633,19 @@ final class CoreLibsDebugSupportTest extends TestCase if ($replace === null && $flag === null) { $this->assertEquals( $expected, - \CoreLibs\Debug\Support::debugString($input), + Support::debugString($input), 'assert all default' ); } elseif ($flag === null) { $this->assertEquals( $expected, - \CoreLibs\Debug\Support::debugString($input, $replace), + Support::debugString($input, $replace), 'assert flag default' ); } else { $this->assertEquals( $expected, - \CoreLibs\Debug\Support::debugString($input, $replace, $flag), + Support::debugString($input, $replace, $flag), 'assert all set' ); } diff --git a/4dev/tests/Logging/CoreLibsLoggingLoggingTest.php b/4dev/tests/Logging/CoreLibsLoggingLoggingTest.php new file mode 100644 index 00000000..9851722a --- /dev/null +++ b/4dev/tests/Logging/CoreLibsLoggingLoggingTest.php @@ -0,0 +1,797 @@ + [ + 'options' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp', + 'log_file_id' => 'testClassInit', + ], + 'expected' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + 'log_level' => Level::Debug, + 'log_file_id' => 'testClassInit', + ], + 'override' => [], + ], + // -> deprecation warning, log_folder must be set + 'no log folder set' => [ + 'options' => [ + 'log_file_id' => 'testClassInit' + ], + 'expected' => [ + 'log_folder' => getcwd() . DIRECTORY_SEPARATOR, + 'log_level' => Level::Debug, + 'log_file_id' => 'testClassInit', + ], + 'override' => [] + ], + // -> upcoming deprecated + 'file_id set but not log_file_id' => [ + 'options' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + 'file_id' => 'testClassInit', + ], + 'expected' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + 'log_level' => Level::Debug, + 'log_file_id' => 'testClassInit', + ], + 'override' => [], + ], + // both file_id and log_file_id set -> WARNING + 'file_id and log_file_id set' => [ + 'options' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + 'file_id' => 'testClassInit', + 'log_file_id' => 'testClassInit', + ], + 'expected' => [ + 'log_folder' => DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + 'log_level' => Level::Debug, + 'log_file_id' => 'testClassInit', + ], + 'override' => [], + ], + // no log file id set -> error, + /* 'nothing set' => [ + 'options' => [], + 'expected' => [ + 'log_folder' => getcwd() . DIRECTORY_SEPARATOR, + 'log_level' => Level::Debug, + 'log_file_id' => 'NOHOST-NOPORT_PHPUnit-TextUI-Command', + ], + 'override' => [] + ] */ + ]; + } + + /** + * init logging class + * + * @dataProvider optionsProvider + * @testdox init test [$_dataName] + * + * @param array $options + * @param array $expected + * @param array $override + * @return void + */ + public function testClassInit(array $options, array $expected, array $override): void + { + if (!empty($override['constant'])) { + foreach ($override['constant'] as $var => $value) { + if (!defined($var)) { + define($var, $value); + } + } + // for deprecated no log_folder set + // if base is defined and it does have AAASetupData set + // change the log_folder "Debug" to "AAASetupData" + if ( + defined('BASE') && + strpos(BASE, DIRECTORY_SEPARATOR . 'AAASetupData') !== false + ) { + $expected['log_folder'] = str_replace( + DIRECTORY_SEPARATOR . 'Debug', + DIRECTORY_SEPARATOR . 'AAASetupData', + $expected['log_folder'] + ); + } + } + // if not log folder and constant set -> expect E_USER_DEPRECATION + if (!empty($override['constant']) && empty($options['log_folder'])) { + // the deprecation message + $deprecation_message = 'options: log_folder must be set. ' + . 'Setting via BASE and LOG constants is deprecated'; + // convert E_USER_DEPRECATED to a exception + set_error_handler( + static function (int $errno, string $errstr): never { + throw new \Exception($errstr, $errno); + }, + E_USER_DEPRECATED + ); + // catch this with the message + $this->expectExceptionMessage($deprecation_message); + } + // alert for log file id with globals + if (!empty($override['constant']) && empty($options['log_file_id'])) { + // + } + // alert for log file id and file id set + if ( + !empty($options['log_file_id']) && + !empty($options['file_id']) + ) { + set_error_handler( + static function (int $errno, string $errstr): never { + throw new \InvalidArgumentException($errstr, $errno); + }, + E_USER_WARNING + ); + $error_message = 'options: "file_id" is deprecated use: "log_file_id".'; + $this->expectExceptionMessage($error_message); + $this->expectException(\InvalidArgumentException::class); + set_error_handler( + static function (int $errno, string $errstr): never { + throw new \Exception($errstr, $errno); + }, + E_USER_DEPRECATED + ); + $this->expectException(\Exception::class); + // $error_message = 'options: both log_file_id and log_id are set at the same time, will use log_file_id'; + // $this->expectExceptionMessage($error_message); + } + // empty log folder + if (empty($override['constant']) && empty($options['log_folder'])) { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessageMatches("/^Missing mandatory option: \"/"); + } elseif (empty($options['log_file_id']) && !empty($options['file_id'])) { + // the deprecation message + $deprecation_message = 'options: "file_id" is deprecated use: "log_file_id".'; + // convert E_USER_DEPRECATED to a exception + set_error_handler( + static function (int $errno, string $errstr): never { + throw new \Exception($errstr, $errno); + }, + E_USER_DEPRECATED + ); + // catch this with the message + $this->expectExceptionMessage($deprecation_message); + } + $log = new \CoreLibs\Logging\Logging($options); + // reset error handler + restore_error_handler(); + // check that settings match + $this->assertEquals( + $expected['log_folder'], + $log->getLogFolder(), + 'log folder not matching' + ); + $this->assertEquals( + $expected['log_file_id'], + $log->getLogFileId(), + 'log file id not matching' + ); + } + + // test all setters/getters + + // setLoggingLevel + // getLoggingLevel + // getJsDebug + + /** + * Undocumented function + * + * @covers ::setLoggingLevel + * @covers ::getLoggingLevel + * @covers ::getJsDebug + * @testdox setLoggingLevel set/get checks + * + * @return void + */ + public function testSetLoggingLevel(): void + { + // valid that is not Debug + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLoggingLevel', + 'log_folder' => self::LOG_FOLDER, + 'log_level' => Level::Info + ]); + $this->assertEquals( + Level::Info, + $log->getLoggingLevel() + ); + $this->assertFalse( + $log->getJsDebug() + ); + // not set, should be debug] + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLoggingLevel', + 'log_folder' => self::LOG_FOLDER, + ]); + $this->assertEquals( + Level::Debug, + $log->getLoggingLevel() + ); + $this->assertTrue( + $log->getJsDebug() + ); + // invalid, should be debug, will throw excpetion too + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Option: "log_level" is not of instance \CoreLibs\Logging\Logger\Level'); + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLoggingLevel', + 'log_folder' => self::LOG_FOLDER, + 'log_level' => 'I' + ]); + $this->assertEquals( + Level::Debug, + $log->getLoggingLevel() + ); + $this->assertTrue( + $log->getJsDebug() + ); + // set valid, then change + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLoggingLevel', + 'log_folder' => self::LOG_FOLDER, + 'log_level' => Level::Info + ]); + $this->assertEquals( + Level::Info, + $log->getLoggingLevel() + ); + $log->setLoggingLevel(Level::Notice); + $this->assertEquals( + Level::Notice, + $log->getLoggingLevel() + ); + // illegal logging level + $this->expectException(\Psr\Log\InvalidArgumentException::class); + $this->expectExceptionMessageMatches("/^Level \"NotGood\" is not defined, use one of: /"); + $log->setLoggingLevel('NotGood'); + } + + // setLogFileId + // getLogFileId + + /** + * Undocumented function + * + * @covers ::setLogFileId + * @covers ::getLogFileId + * @testdox setLogFileId set/get checks + * + * @return void + */ + public function testLogFileId(): void + { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testLogFileId', + 'log_folder' => self::LOG_FOLDER + ]); + // bad, keep same + $log->setLogFileId('$$##$%#$%&'); + $this->assertEquals( + 'testLogFileId', + $log->getLogFileId() + ); + // good, change + $log->setLogFileId('validID'); + $this->assertEquals( + 'validID', + $log->getLogFileId() + ); + // invalid on init + $this->expectException(\Psr\Log\InvalidArgumentException::class); + $this->expectExceptionMessage('LogFileId: no log file id set'); + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => '$$$"#"#$"#$', + 'log_folder' => self::LOG_FOLDER + ]); + } + + // setLogUniqueId + // getLogUniqueId + + /** + * Undocumented function + * + * @return array + */ + public function logUniqueIdProvider(): array + { + return [ + 'option set' => [ + 'option' => true, + 'override' => false, + ], + 'direct set' => [ + 'option' => false, + 'override' => false, + ], + 'override set' => [ + 'option' => false, + 'override' => true, + ], + 'option and override set' => [ + 'option' => false, + 'override' => true, + ], + ]; + } + + /** + * Undocumented function + * + * @covers ::setLogUniqueId + * @covers ::getLogUniqueId + * @dataProvider logUniqueIdProvider + * @testdox per run log id set test: option: $option, override: $override [$_dataName] + * + * @param bool $option + * @param bool $override + * @return void + */ + public function testLogUniqueId(bool $option, bool $override): void + { + if ($option === true) { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testLogUniqueId', + 'log_folder' => self::LOG_FOLDER, + 'log_per_run' => $option + ]); + } else { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testLogUniqueId', + 'log_folder' => self::LOG_FOLDER + ]); + $log->setLogUniqueId(); + } + $per_run_id = $log->getLogUniqueId(); + $this->assertMatchesRegularExpression( + "/^\d{4}-\d{2}-\d{2}_\d{6}_U_[a-z0-9]{8}$/", + $per_run_id, + 'assert per log run id 1st' + ); + if ($override === true) { + $log->setLogUniqueId(true); + $per_run_id_2nd = $log->getLogUniqueId(); + $this->assertMatchesRegularExpression( + "/^\d{4}-\d{2}-\d{2}_\d{6}_U_[a-z0-9]{8}$/", + $per_run_id_2nd, + 'assert per log run id 2nd' + ); + $this->assertNotEquals( + $per_run_id, + $per_run_id_2nd, + '1st and 2nd don\'t match' + ); + } + } + + // setLogDate + // getLogDate + + /** + * Undocumented function + * + * @covers ::setLogDate + * @covers ::getLogDate + * @testdox setLogDate set/get checks + * + * @return void + */ + public function testSetLogDate(): void + { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testLogFileId', + 'log_folder' => self::LOG_FOLDER, + 'log_per_date' => true, + ]); + $this->assertEquals( + date('Y-m-d'), + $log->getLogDate() + ); + } + + // setLogFlag + // getLogFlag + // unsetLogFlag + // getLogFlags + // Logger\Flag + + /** + * Undocumented function + * + * @covers Logger\Flag + * @testdox Logger\Flag enum test + * + * @return void + */ + public function testLoggerFlag(): void + { + // logger flags to check that they exist + $flags = [ + 'all_off' => 0, + 'per_run' => 1, + 'per_date' => 2, + 'per_group' => 4, + 'per_page' => 8, + 'per_class' => 16, + 'per_level' => 32, + ]; + // from int -> return value + foreach ($flags as $name => $value) { + $this->assertEquals( + Flag::fromName($name), + Flag::fromValue($value) + ); + } + } + + /** + * Undocumented function + * + * @covers ::setLogFlag + * @covers ::getLogFlag + * @covers ::unsetLogFlag + * @covers ::getLogFlags + * @testdox setLogDate set/get checks + * + * @return void + */ + public function testSetLogFlag(): void + { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLogFlag', + 'log_folder' => self::LOG_FOLDER, + ]); + // set valid log flag + $log->setLogFlag(Flag::per_run); + $this->assertTrue( + $log->getLogFlag(Flag::per_run) + ); + // flags seum + $this->assertEquals( + Flag::per_run->value, + $log->getLogFlags(), + ); + // unset valid log flag + $log->unsetLogFlag(Flag::per_run); + $this->assertFalse( + $log->getLogFlag(Flag::per_run) + ); + // illegal Flags cannot be set, they will throw eerros onrun + + // test multi set and sum is equals set + $log->setLogFlag(Flag::per_date); + $log->setLogFlag(Flag::per_group); + $this->assertEquals( + Flag::per_date->value + Flag::per_group->value, + $log->getLogFlags() + ); + } + + // setLogFolder + // getLogFolder + + /** + * Undocumented function + * + * @covers ::setLogFolder + * @covers ::getLogFolder + * @testdox setLogFolder set/get checks, init check + * + * @return void + */ + public function testSetLogFolder(): void + { + // set to good folder + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLogFolder', + 'log_folder' => self::LOG_FOLDER, + ]); + $this->assertEquals( + self::LOG_FOLDER, + $log->getLogFolder() + ); + // set to a good other folder + $log->setLogFolder(DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR); + $this->assertEquals( + DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + $log->getLogFolder() + ); + // good other folder with missing trailing slash + $log->setLogFolder(DIRECTORY_SEPARATOR . 'tmp'); + $this->assertEquals( + DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + $log->getLogFolder() + ); + // a bad folder -> last good folder + $log->setLogFolder('I-am-not existing'); + $this->assertEquals( + DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, + $log->getLogFolder() + ); + // init with a bad folder + $this->expectException(\Psr\Log\InvalidArgumentException::class); + $this->expectExceptionMessage('Folder: "I-am-bad" is not writeable for logging'); + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLogFolderInvalid', + 'log_folder' => 'I-am-bad', + ]); + } + + // getLogFile (no set, only correct after log run) + + // setLogMaxFileSize + // getLogMaxFileSize + + /** + * Undocumented function + * + * @covers ::setLogMaxFileSize + * @covers ::getLogMaxFileSize + * @testdox setLogMaxFileSize set/get checks, init check + * + * @return void + */ + public function testSetLogMaxFileSize(): void + { + // init set to 0 + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testSetLogMaxFileSize', + 'log_folder' => self::LOG_FOLDER, + ]); + $this->assertEquals( + 0, + $log->getLogMaxFileSize() + ); + // set to new, valid size + $file_size = 200 * 1024; + $valid = $log->setLogMaxFileSize($file_size); + $this->assertTrue($valid); + $this->assertEquals( + $file_size, + $log->getLogMaxFileSize() + ); + // invalid size, < 0, will be last and return false + $valid = $log->setLogMaxFileSize(-1); + $this->assertFalse($valid); + $this->assertEquals( + $file_size, + $log->getLogMaxFileSize() + ); + // too small (< MIN_LOG_MAX_FILESIZE) + $valid = $log->setLogMaxFileSize($log::MIN_LOG_MAX_FILESIZE - 1); + $this->assertFalse($valid); + $this->assertEquals( + $file_size, + $log->getLogMaxFileSize() + ); + } + + // getOption (option params) + + /** + * Undocumented function + * + * @covers ::getOption + * @testdox getOption checks + * + * @return void + */ + public function testGetOption(): void + { + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testGetOption', + 'log_folder' => self::LOG_FOLDER, + ]); + $this->assertEquals( + self::LOG_FOLDER, + $log->getOption('log_folder') + ); + // not found + $this->assertNull( + $log->getOption('I_do not exist') + ); + } + + // test all logger functions + // debug (special) + // info + // notice + // warning + // error + // critical + // alert + // emergency + + /** + * Undocumented function + * + * @covers ::debug + * @testdox debug checks + * + * @return void + */ + public function testDebug(): void + { + // init logger + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'testDebug', + 'log_folder' => self::LOG_FOLDER, + ]); + // clean all data in folder first + array_map('unlink', glob($log->getLogFolder() . $log->getLogFileId() . '*.log')); + + $group_id = 'G'; + $message = 'D'; + $log_status = $log->debug($group_id, $message); + $this->assertTrue($log_status, 'debug write successful'); + $file_content = file_get_contents( + $log->getLogFolder() . $log->getLogFile() + ) ?: ''; + $log_level = $log->getLoggingLevel()->getName(); + // [2023-05-30 15:51:39.36128800] [NOHOST:NOPORT] + // [www/vendor/bin/phpunit] [7b9d0747] {PHPUnit\TextUI\Command} + // D + $this->assertMatchesRegularExpression( + "/" . self::REGEX_BASE + . "<$log_level:$group_id>\s{1}" // log level / group id + . "$message" // message + . "/", + $file_content + ); + } + + public function providerLoggingLevelWrite(): array + { + return [ + 'info' => [ + 'message' => 'I', + 'file_id' => Level::Info->name, + 'level' => Level::Info + ], + 'notice' => [ + 'message' => 'N', + 'file_id' => Level::Notice->name, + 'level' => Level::Notice + ], + 'warning' => [ + 'message' => 'W', + 'file_id' => Level::Warning->name, + 'level' => Level::Warning + ], + 'error' => [ + 'message' => 'E', + 'file_id' => Level::Error->name, + 'level' => Level::Error + ], + 'crticial' => [ + 'message' => 'C', + 'file_id' => Level::Critical->name, + 'level' => Level::Critical + ], + 'alert' => [ + 'message' => 'A', + 'file_id' => Level::Alert->name, + 'level' => Level::Alert + ], + 'emergency' => [ + 'message' => 'Em', + 'file_id' => Level::Emergency->name, + 'level' => Level::Emergency + ], + ]; + } + + /** + * Undocumented function + * + * @covers ::info + * @covers ::notice + * @covers ::warning + * @covers ::error + * @covers ::critical + * @covers ::alert + * @covers ::emergency + * @dataProvider providerLoggingLevelWrite + * @testdox logging level write checks for $level [$_dataName] + * + * @return void + */ + public function testLoggingLevelWrite(string $message, string $file_id, Level $level): void + { + // init logger + $log = new \CoreLibs\Logging\Logging([ + 'log_file_id' => 'test' . $file_id, + 'log_folder' => self::LOG_FOLDER, + 'log_level' => $level, + ]); + // clean all data in folder first + array_map('unlink', glob($log->getLogFolder() . $log->getLogFileId() . '*.log')); + + switch ($level->value) { + case 200: + $log_status = $log->info($message); + break; + case 250: + $log_status = $log->notice($message); + break; + case 300: + $log_status = $log->warning($message); + break; + case 400: + $log_status = $log->error($message); + break; + case 500: + $log_status = $log->critical($message); + break; + case 550: + $log_status = $log->alert($message); + break; + case 600: + $log_status = $log->emergency($message); + break; + } + $this->assertTrue($log_status, 'log write successful'); + $file_content = file_get_contents( + $log->getLogFolder() . $log->getLogFile() + ) ?: ''; + $log_level = $log->getLoggingLevel()->getName(); + $this->assertMatchesRegularExpression( + "/" . self::REGEX_BASE + . "<$log_level>\s{1}" // log level / group id + . "$message" // message + . "/", + $file_content, + 'log message regex' + ); + } + + // deprecated calls check? +} + +// __END__ diff --git a/4dev/tests/Logging/log/.gitignore b/4dev/tests/Logging/log/.gitignore new file mode 100644 index 00000000..2a50fc00 --- /dev/null +++ b/4dev/tests/Logging/log/.gitignore @@ -0,0 +1,3 @@ +*log +*LOG +!.gitignore diff --git a/www/admin/class_test.admin.backend.php b/www/admin/class_test.admin.backend.php index a37fe5fe..1786b8b8 100644 --- a/www/admin/class_test.admin.backend.php +++ b/www/admin/class_test.admin.backend.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -27,15 +22,10 @@ $SET_SESSION_NAME = EDIT_SESSION_NAME; ob_end_flush(); $session = new CoreLibs\Create\Session($SET_SESSION_NAME); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); // db config with logger $db = new CoreLibs\DB\IO(DB_CONFIG, $log); @@ -72,9 +62,6 @@ $backend->adbMsg('info', 'Message: %1$d', [1]); print "Messaes: " . Support::printAr($backend->messages) . "
"; print "ADBPRINTDATETIME:
" . $backend->adbPrintDateTime(2021, 6, 21, 6, 38, '_test') . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.array.php b/www/admin/class_test.array.php index d6f31290..eef96c21 100644 --- a/www/admin/class_test.array.php +++ b/www/admin/class_test.array.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -27,15 +22,10 @@ use CoreLibs\Combined\ArrayHandler; use CoreLibs\Debug\Support as DgS; use CoreLibs\Convert\SetVarType; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); // $_array = new CoreLibs\Combined\ArrayHandler(); // $array_class = 'CoreLibs\Combination\ArrayHandler'; @@ -246,9 +236,6 @@ $flag = false; $output = \CoreLibs\Combined\ArrayHandler::genAssocArray($db_array, $key, $value, $flag); print "OUTPUT: " . \CoreLibs\Debug\Support::printAr($output) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.autoloader.php b/www/admin/class_test.autoloader.php index 97835ec1..284a7861 100644 --- a/www/admin/class_test.autoloader.php +++ b/www/admin/class_test.autoloader.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); diff --git a/www/admin/class_test.byte.php b/www/admin/class_test.byte.php index 1e5e0340..669070cb 100644 --- a/www/admin/class_test.byte.php +++ b/www/admin/class_test.byte.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Convert\Byte; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $byte_class = 'CoreLibs\Convert\Byte'; @@ -104,9 +94,6 @@ foreach ($bytes as $byte) { print ""; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.check.colors.php b/www/admin/class_test.check.colors.php index 69b1195a..130f6af2 100644 --- a/www/admin/class_test.check.colors.php +++ b/www/admin/class_test.check.colors.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Check\Colors; // use CoreLibs\Debug\Support as DgS; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: CHECK COLORS'; @@ -113,9 +103,6 @@ try { print "ERROR: " . $e->getCode() . ": " . $e->getMessage() . "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.config.direct.php b/www/admin/class_test.config.direct.php index 9653d4df..95d85624 100644 --- a/www/admin/class_test.config.direct.php +++ b/www/admin/class_test.config.direct.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require '../configs/config.php'; $LOG_FILE_ID = 'classTest-config-direct'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: CONFIG DIRECT'; @@ -49,9 +39,6 @@ echo "Config path prefix: " . ($CONFIG_PATH_PREFIX ?? '') . "
"; print "DB Name: " . DB_CONFIG_NAME . "
"; print "DB Config: " . \CoreLibs\Debug\Support::printAr(DB_CONFIG) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.config.link.php b/www/admin/class_test.config.link.php index a1efad74..cfe812fc 100644 --- a/www/admin/class_test.config.link.php +++ b/www/admin/class_test.config.link.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-config-link'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: CONFIG LINK'; @@ -49,9 +39,6 @@ echo "Config path prefix: " . ($CONFIG_PATH_PREFIX ?? '') . "
"; print "DB Name: " . DB_CONFIG_NAME . "
"; print "DB Config: " . \CoreLibs\Debug\Support::printAr(DB_CONFIG) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.convert.colors.php b/www/admin/class_test.convert.colors.php index e1b88241..223d152e 100644 --- a/www/admin/class_test.convert.colors.php +++ b/www/admin/class_test.convert.colors.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -27,15 +22,10 @@ use CoreLibs\Convert\Colors; use CoreLibs\Debug\Support as DgS; use CoreLibs\Convert\SetVarType; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $color_class = 'CoreLibs\Convert\Colors'; @@ -104,9 +94,6 @@ print "RANDOM hsl->rgb:
" . DgS::printAr(SetVarType::setArray(Colors::hsl2r
 
 // TODO: run compare check input must match output
 
-// error message
-print $log->printErrorMsg();
-
 print "";
 
 // __END__
diff --git a/www/admin/class_test.create_email.php b/www/admin/class_test.create_email.php
index 9ea99671..085cd391 100644
--- a/www/admin/class_test.create_email.php
+++ b/www/admin/class_test.create_email.php
@@ -6,13 +6,6 @@
 
 declare(strict_types=1);
 
-// will be overwritten in config.master.php depending on location
-$DEBUG_ALL_OVERRIDE = true; // set to 1 to debug on live/remote server locations
-$DEBUG_ALL = true;
-$PRINT_ALL = true;
-$ECHO_ALL = true;
-$DB_DEBUG = true;
-
 error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
 
 ob_start();
@@ -30,15 +23,10 @@ $ECHO_ALL = true;
 use CoreLibs\Create\Email;
 use CoreLibs\Convert\Html;
 
-$log = new CoreLibs\Debug\Logging([
+$log = new CoreLibs\Logging\Logging([
 	'log_folder' => BASE . LOG,
-	'file_id' => $LOG_FILE_ID,
-	// add file date
-	'print_file_date' => true,
-	// set debug and print flags
-	'debug_all' => $DEBUG_ALL,
-	'echo_all' => $ECHO_ALL,
-	'print_all' => $PRINT_ALL,
+	'log_file_id' => $LOG_FILE_ID,
+	'log_per_date' => true,
 ]);
 
 // define a list of from to color sets for conversion test
@@ -134,9 +122,6 @@ $status = Email::sendEmail(
 );
 print "SENDING D: " . $status . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.datetime.php b/www/admin/class_test.datetime.php index a723ca52..56c8854d 100644 --- a/www/admin/class_test.datetime.php +++ b/www/admin/class_test.datetime.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Combined\DateTime; use CoreLibs\Debug\Support as DgS; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $datetime_class = 'CoreLibs\Combined\DateTime'; @@ -153,9 +143,6 @@ print "DATE-dow[$date];invalid: " . DateTime::setWeekdayNameFromDate($date) . "< print "DATE-dow[$date],long;invalid: " . DateTime::setWeekdayNameFromDate($date, true) . "
"; print "DOW-date[$date];invalid: " . DateTime::setWeekdayNumberFromDate($date) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.db.dbReturn.php b/www/admin/class_test.db.dbReturn.php index 8ca37fdb..c9d5a219 100644 --- a/www/admin/class_test.db.dbReturn.php +++ b/www/admin/class_test.db.dbReturn.php @@ -15,8 +15,6 @@ ob_start(); define('USE_DATABASE', true); // sample config require 'config.php'; -// override ECHO ALL FALSE -$ECHO_ALL = true; // define log file id $LOG_FILE_ID = 'classTest-db'; ob_end_flush(); @@ -25,15 +23,10 @@ use CoreLibs\Debug\Support; use CoreLibs\Debug\RunningTime; use CoreLibs\Convert\SetVarType; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL ?? true, - 'echo_all' => $ECHO_ALL, - 'print_all' => $PRINT_ALL ?? true, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); // db connection and attach logger $db = new CoreLibs\DB\IO(DB_CONFIG, $log); @@ -47,8 +40,8 @@ print '
Class Test Master
'; print '
Class Test DB
'; print '

' . $PAGE_NAME . '

'; -print "LOGFILE NAME: " . $db->log->getSetting('log_file_name') . "
"; -print "LOGFILE ID: " . $db->log->getSetting('log_file_id') . "
"; +print "LOGFILE NAME: " . $db->log->getLogFile() . "
"; +print "LOGFILE ID: " . $db->log->getLogFileId() . "
"; print "DBINFO: " . $db->dbInfo() . "
"; // DB client encoding @@ -74,9 +67,9 @@ for ($i = 1; $i <= 6; $i++) { $res = $db->dbReturn($q_db_ret); print $i . ") " . $cache_flag . ": " . "res: " . (is_bool($res) ? - "Bool: " . $db->log->prBl($res) : + "Bool: " . Support::prBl($res) : (is_array($res) ? - "Array: " . $db->log->prBl(is_array($res)) : '{-}') + "Array: " . Support::prBl(is_array($res)) : '{-}') ) . ", " . "cursor_ext:
" . Support::printAr(
 			SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
@@ -93,9 +86,9 @@ for ($i = 1; $i <= 6; $i++) {
 	$res = $db->dbReturn($q_db_ret, $db::USE_CACHE);
 	print $i . ") " . $cache_flag . ": "
 		. "res: " . (is_bool($res) ?
-			"Bool: " . $db->log->prBl($res) :
+			"Bool: " . Support::prBl($res) :
 			(is_array($res) ?
-				"Array: " . $db->log->prBl(is_array($res)) : '{-}')
+				"Array: " . Support::prBl(is_array($res)) : '{-}')
 		) . ", "
 		. "cursor_ext: 
" . Support::printAr(
 			SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
@@ -112,9 +105,9 @@ for ($i = 1; $i <= 6; $i++) {
 	$res = $db->dbReturn($q_db_ret, $db::READ_NEW);
 	print $i . ") " . $cache_flag . ": "
 		. "res: " . (is_bool($res) ?
-			"Bool: " . $db->log->prBl($res) :
+			"Bool: " . Support::prBl($res) :
 			(is_array($res) ?
-				"Array: " . $db->log->prBl(is_array($res)) : '{-}')
+				"Array: " . Support::prBl(is_array($res)) : '{-}')
 		) . ", "
 		. "cursor_ext: 
" . Support::printAr(
 			SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
@@ -131,9 +124,9 @@ for ($i = 1; $i <= 6; $i++) {
 	$res = $db->dbReturn($q_db_ret, $db::CLEAR_CACHE);
 	print $i . ") " . $cache_flag . ": "
 		. "res: " . (is_bool($res) ?
-			"Bool: " . $db->log->prBl($res) :
+			"Bool: " . Support::prBl($res) :
 			(is_array($res) ?
-				"Array: " . $db->log->prBl(is_array($res)) : '{-}')
+				"Array: " . Support::prBl(is_array($res)) : '{-}')
 		) . ", "
 		. "cursor_ext: 
" . Support::printAr(
 			SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
@@ -150,9 +143,9 @@ for ($i = 1; $i <= 6; $i++) {
 	$res = $db->dbReturn($q_db_ret, $db::NO_CACHE);
 	print $i . ") " . $cache_flag . ": "
 		. "res: " . (is_bool($res) ?
-			"Bool: " . $db->log->prBl($res) :
+			"Bool: " . Support::prBl($res) :
 			(is_array($res) ?
-				"Array: " . $db->log->prBl(is_array($res)) : '{-}')
+				"Array: " . Support::prBl(is_array($res)) : '{-}')
 		) . ", "
 		. "cursor_ext: 
" . Support::printAr(
 			SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
diff --git a/www/admin/class_test.db.php b/www/admin/class_test.db.php
index d95689ac..adb6e8b9 100644
--- a/www/admin/class_test.db.php
+++ b/www/admin/class_test.db.php
@@ -15,8 +15,6 @@ ob_start();
 define('USE_DATABASE', true);
 // sample config
 require 'config.php';
-// override ECHO ALL FALSE
-$ECHO_ALL = true;
 // define log file id
 $LOG_FILE_ID = 'classTest-db';
 ob_end_flush();
@@ -26,15 +24,10 @@ use CoreLibs\DB\IO as DbIo;
 use CoreLibs\Debug\Support;
 use CoreLibs\Convert\SetVarType;
 
-$log = new CoreLibs\Debug\Logging([
+$log = new CoreLibs\Logging\Logging([
 	'log_folder' => BASE . LOG,
-	'file_id' => $LOG_FILE_ID,
-	// add file date
-	'print_file_date' => true,
-	// set debug and print flags
-	'debug_all' => $DEBUG_ALL ?? true,
-	'echo_all' => $ECHO_ALL,
-	'print_all' => $PRINT_ALL ?? true,
+	'log_file_id' => $LOG_FILE_ID,
+	'log_per_date' => true,
 ]);
 // db connection and attach logger
 $db = new CoreLibs\DB\IO(DB_CONFIG, $log);
@@ -48,8 +41,8 @@ print '';
 print '';
 print '

' . $PAGE_NAME . '

'; -print "LOGFILE NAME: " . $db->log->getSetting('log_file_name') . "
"; -print "LOGFILE ID: " . $db->log->getSetting('log_file_id') . "
"; +print "LOGFILE NAME: " . $db->log->getLogFile() . "
"; +print "LOGFILE ID: " . $db->log->getLogFileId() . "
"; print "DBINFO: " . $db->dbInfo() . "
"; echo "DB_CONFIG_SET constant:
" . print_r(DB_CONFIG, true) . "

"; @@ -790,9 +783,6 @@ print "RES: " . DgS::printAr(SetVarType::setArray($res)) . "
"; print "ISSET: " . isset($res['null_varchar']) . "
"; print "EMPTY: " . empty($res['null_varchar']) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.db.single.php b/www/admin/class_test.db.single.php index 778e2730..e288cd7a 100644 --- a/www/admin/class_test.db.single.php +++ b/www/admin/class_test.db.single.php @@ -15,23 +15,16 @@ ob_start(); define('USE_DATABASE', true); // sample config require 'config.php'; -// override ECHO ALL FALSE -$ECHO_ALL = true; // define log file id $LOG_FILE_ID = 'classTest-db-single'; ob_end_flush(); use CoreLibs\Debug\Support; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL ?? true, - 'echo_all' => $ECHO_ALL, - 'print_all' => $PRINT_ALL ?? true, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); // db connection and attach logger $db = new CoreLibs\DB\IO(DB_CONFIG, $log); @@ -45,8 +38,8 @@ print ''; print ''; print '

' . $PAGE_NAME . '

'; -print "LOGFILE NAME: " . $db->log->getSetting('log_file_name') . "
"; -print "LOGFILE ID: " . $db->log->getSetting('log_file_id') . "
"; +print "LOGFILE NAME: " . $db->log->getLogFile() . "
"; +print "LOGFILE ID: " . $db->log->getLogFileId() . "
"; print "DBINFO: " . $db->dbInfo() . "
"; // DB client encoding print "DB client encoding: " . $db->dbGetEncoding() . "
"; @@ -94,9 +87,6 @@ echo "EOM STRING WITH MORE THAN 10 PARAMETERS: " . "ERROR: " . $db->dbGetLastError(true) . "
"; echo "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.debug.php b/www/admin/class_test.debug.php index 02a4c2d9..09325d39 100644 --- a/www/admin/class_test.debug.php +++ b/www/admin/class_test.debug.php @@ -7,7 +7,6 @@ declare(strict_types=1); // all the settings are overruled by config -$DEBUG_ALL_OVERRIDE = true; // set to 1 to debug on live/remote server locations $DEBUG_ALL = true; $PRINT_ALL = false; $ECHO_ALL = true; @@ -32,7 +31,7 @@ $ECHO_ALL = true; use CoreLibs\Debug\Support as DebugSupport; use CoreLibs\Debug\FileWriter; -$debug = new CoreLibs\Debug\Logging([ +$debug = new CoreLibs\Debug\LoggingLegacy([ 'log_folder' => BASE . LOG, 'file_id' => $LOG_FILE_ID, 'debug_all' => $DEBUG_ALL, @@ -40,7 +39,7 @@ $debug = new CoreLibs\Debug\Logging([ 'echo_all' => $ECHO_ALL, ]); $debug_support_class = 'CoreLibs\Debug\Support'; -$debug_logging_class = 'CoreLibs\Debug\Logging'; +$debug_logging_class = 'CoreLibs\Debug\LoggingLegacy'; $PAGE_NAME = 'TEST CLASS: DEBUG'; print ""; @@ -72,16 +71,43 @@ function test2(): array print "S::GETCALLERMETHOD: " . DebugSupport::getCallerMethod(0) . "
"; print "S::GETCALLERMETHOD: " . test() . "
"; print "S::GETCALLERMETHODLIST:
" . print_r(test2(), true) . "

"; +// printAr print "S::PRINTAR: " . DebugSupport::printAr(['Foo', 'Bar']) . "
"; print "V-S::PRINTAR: " . $debug_support_class::printAr(['Foo', 'Bar']) . "
"; +// printBool print "S::PRINTBOOL(default): " . DebugSupport::printBool(true) . "
"; print "S::PRINTBOOL(name): " . DebugSupport::printBool(true, 'Name') . "
"; print "S::PRINTBOOL(name, ok): " . DebugSupport::printBool(true, 'Name', 'ok') . "
"; print "S::PRINTBOOL(name, ok, not): " . DebugSupport::printBool(false, 'Name', 'ok', 'not') . "
"; +// debugString +print "S::DEBUSTRING(s): " . DebugSupport::debugString('SET') . "
"; print "S::DEBUSTRING(s): " . DebugSupport::debugString('SET') . "
"; print "S::DEBUSTRING(s>): " . DebugSupport::debugString('') . "
"; print "S::DEBUSTRING(''): " . DebugSupport::debugString('') . "
"; print "S::DEBUSTRING(,s): " . DebugSupport::debugString(null, '{-}') . "
"; +// dumpVar +print "S::DUMPVAR(s): " . DebugSupport::dumpVar('SET') . "
"; +print "S::DUMPVAR(s,true): " . DebugSupport::dumpVar('SET', true) . "
"; +print "S::DUMPVAR(s>): " . DebugSupport::dumpVar('') . "
"; +print "S::DUMPVAR(s>,true): " . DebugSupport::dumpVar('', true) . "
"; +print "S::DUMPVAR(''): " . DebugSupport::dumpVar('') . "
"; +print "S::DUMPVAR(,s): " . DebugSupport::dumpVar(null) . "
"; +print "S::DUMPVAR([a,b]): " . DebugSupport::dumpVar(['a', 'b']) . "
"; +print "S::DUMPVAR([a,b],true): " . DebugSupport::dumpVar(['a', 'b'], true) . "
"; +print "S::DUMPVAR([MIXED]): " . DebugSupport::dumpVar(<<block +and > and < +EOM) . "
"; +// exportVar +// print "S::EXPORTVAR(s): " . DebugSupport::exportVar('SET') . "
"; +// print "S::EXPORTVAR(s>): " . DebugSupport::exportVar('') . "
"; +// print "S::EXPORTVAR(''): " . DebugSupport::exportVar('') . "
"; +// print "S::EXPORTVAR(,s): " . DebugSupport::exportVar(null) . "
"; +// print "S::EXPORTVAR([a,b]): " . DebugSupport::exportVar(['a', 'b']) . "
"; +// print "S::EXPORTVAR([a,b],true): " . DebugSupport::exportVar(['a', 'b']) . "
"; // get test print "LOG FOLDER: " . $debug->getSetting('log_folder') . "
"; @@ -95,7 +121,7 @@ print "C->PRINTERRORMSG:
" . $debug->printErrorMsg() . "
"; echo "OPTIONS DEBUG CALL
"; // new log type with options -$new_log = new CoreLibs\Debug\Logging([ +$new_log = new CoreLibs\Debug\LoggingLegacy([ 'log_folder' => '../log/', 'file_id' => 'DebugTestNewLogger', // add file date @@ -125,11 +151,11 @@ echo "CLASS DEBUG CALL
"; // @codingStandardsIgnoreLine class TestL { - /** @var \CoreLibs\Debug\Logging */ + /** @var \CoreLibs\Debug\LoggingLegacy */ public $log; public function __construct() { - $this->log = new CoreLibs\Debug\Logging([ + $this->log = new CoreLibs\Debug\LoggingLegacy([ 'log_folder' => '../log/', 'file_id' => 'DebugTestTestLLogger', ]); @@ -186,9 +212,9 @@ print "CLASS EXTEND: PRINTERRORMSG:
" . $tr->log->printErrorMsg() . "
"; // @codingStandardsIgnoreLine class AttachOutside { - /** @var \CoreLibs\Debug\Logging */ + /** @var \CoreLibs\Debug\LoggingLegacy */ public $log; - public function __construct(\CoreLibs\Debug\Logging $logger_class) + public function __construct(\CoreLibs\Debug\LoggingLegacy $logger_class) { $this->log = $logger_class; } @@ -222,6 +248,12 @@ $debug->setLogPer('level', false); $ar = ['A', 1, ['B' => 'D']]; $debug->debug('ARRAY', 'Array: ' . $debug->prAr($ar)); $debug->debug('BOOL', 'True: ' . $debug->prBl(true) . ', False: ' . $debug->prBl(false)); +$debug->debug('MIXED', 'ANYTHING: ' . DebugSupport::dumpVar([ + 'foo' => 1, + 'bar' => null, + 'self' => [1, 2, 3], + 'other' => false +])); // error message // future DEPRECATED diff --git a/www/admin/class_test.email.php b/www/admin/class_test.email.php index 40d5c964..3c258ffb 100644 --- a/www/admin/class_test.email.php +++ b/www/admin/class_test.email.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Check\Email; use CoreLibs\Debug\Support as DgS; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: HTML/ELEMENTS'; @@ -78,9 +68,6 @@ foreach ($email as $s_email) { print "S::CHECKEMAILFULL(true): " . $s_email . ": " . Dgs::printAr(Email::checkEmailFull($s_email, true)) . "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.encoding.php b/www/admin/class_test.encoding.php index 56193bbb..d481597b 100644 --- a/www/admin/class_test.encoding.php +++ b/www/admin/class_test.encoding.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,16 +21,12 @@ ob_end_flush(); use CoreLibs\Convert\Encoding as ConEnc; use CoreLibs\Check\Encoding as ChkEnc; use CoreLibs\Convert\MimeEncode; +use CoreLibs\Debug\Support; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); // class type $_chk_enc = new CoreLibs\Check\Encoding(); @@ -100,10 +91,7 @@ foreach ($enc_strings as $_string) { // static use $_string = $enc_strings[1]; $string = $chk_enc::checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS'); -print "S::ENC CHECK: $_string: " . ($string === false ? '-OK-' : $log->prAr($string)) . "
"; - -// error message -print $log->printErrorMsg(); +print "S::ENC CHECK: $_string: " . ($string === false ? '-OK-' : Support::printAr($string)) . "
"; print ""; diff --git a/www/admin/class_test.encryption.php b/www/admin/class_test.encryption.php index 75185cf4..c03e5515 100644 --- a/www/admin/class_test.encryption.php +++ b/www/admin/class_test.encryption.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,18 +21,12 @@ ob_end_flush(); use CoreLibs\Security\SymmetricEncryption; use CoreLibs\Security\CreateKey; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); - // define a list of from to color sets for conversion test $PAGE_NAME = 'TEST CLASS: ENCRYPTION'; @@ -103,9 +92,6 @@ try { print "Error: " . $e->getMessage() . "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.file.php b/www/admin/class_test.file.php index fa002b09..23ff1422 100644 --- a/www/admin/class_test.file.php +++ b/www/admin/class_test.file.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Check\File; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: FILE'; @@ -48,9 +38,6 @@ print "GETFILENAMEENDING: $file: " . File::getFilenameEnding($file) . "
"; $file = getcwd() . DIRECTORY_SEPARATOR . 'class_test.file.php'; print "GETLINESFROMFILE: $file: " . File::getLinesFromFile($file) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.hash.php b/www/admin/class_test.hash.php index 78e47aa9..0c2d6aeb 100644 --- a/www/admin/class_test.hash.php +++ b/www/admin/class_test.hash.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Create\Hash; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $hash_class = 'CoreLibs\Create\Hash'; @@ -67,9 +57,6 @@ print "HASH LONG: " . $to_crc . ": " . Hash::__hashLong($to_crc) . "
"; // print "UNIQU ID SHORT : " . Hash::__uniqId() . "
"; // print "UNIQU ID LONG : " . Hash::__uniqIdLong() . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.html.php b/www/admin/class_test.html.php index 368498f9..21bf9c1d 100644 --- a/www/admin/class_test.html.php +++ b/www/admin/class_test.html.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Convert\Html; use CoreLibs\Output\Form\Elements; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_html = new CoreLibs\Convert\Html(); $_elements = new CoreLibs\Output\Form\Elements(); @@ -103,9 +93,6 @@ is sucky'; print "LB remove: " . \CoreLibs\Convert\Html::removeLB($text) . "
"; print "LB remove: " . \CoreLibs\Convert\Html::removeLB($text, '##BR##') . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.image.php b/www/admin/class_test.image.php index 43ca790d..a773a5f5 100644 --- a/www/admin/class_test.image.php +++ b/www/admin/class_test.image.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Output\Image; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_image = new CoreLibs\Output\Image(); $image_class = 'CoreLibs\Output\Image'; @@ -95,7 +85,7 @@ foreach ($images as $image) { $image = BASE . LAYOUT . CONTENT_PATH . IMAGES . $image; list ($height, $width, $img_type) = \CoreLibs\Convert\SetVarType::setArray(getimagesize($image)); echo "
IMAGE INFO: " . $height . "x" . $width . ", TYPE: " - . $log->prAr($img_type) . " [" . $finfo->file($image) . "]
"; + . \CoreLibs\Debug\Support::printArray($img_type) . " [" . $finfo->file($image) . "]"; // rotate image first Image::correctImageOrientation($image); // thumbnail tests @@ -119,9 +109,6 @@ foreach ($images as $image) { echo "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.json.php b/www/admin/class_test.json.php index 6b6f46a3..9816abde 100644 --- a/www/admin/class_test.json.php +++ b/www/admin/class_test.json.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Convert\Json; use CoreLibs\Debug\Support as DgS; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $json_class = 'CoreLibs\Convert\Json'; @@ -73,9 +63,6 @@ print "J/S::E-JSON ERROR: " . $json_class::jsonGetLastError() . ": " . $json_cla // print "S::JSON: $json: " . DgS::printAr($output) . "
"; // print "S::JSON ERROR: " . Jason::jsonGetLastError() . ": " . Jason::jsonGetLastError(true) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.lang.php b/www/admin/class_test.lang.php index 622df97d..989bdd02 100644 --- a/www/admin/class_test.lang.php +++ b/www/admin/class_test.lang.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); diff --git a/www/admin/class_test.logging.php b/www/admin/class_test.logging.php new file mode 100644 index 00000000..87f25ac9 --- /dev/null +++ b/www/admin/class_test.logging.php @@ -0,0 +1,94 @@ + BASE . LOG, + 'log_file_id' => $LOG_FILE_ID, + 'log_level' => Level::Debug, + 'log_per_date' => true, +]); + +$PAGE_NAME = 'TEST CLASS: DEBUG LOGGING'; +print ""; +print "" . $PAGE_NAME . ""; +print ""; +print ''; +print '

' . $PAGE_NAME . '

'; + +$log->logger2Debug(); + +print "Level 250: " . Level::fromValue(250)->getName() . "
"; +print "Flag: per_run (from int): " . Flag::fromValue(2)->getName() . "
"; +print "Flag: per_run getName(): " . Flag::per_class->getName() . "
"; +print "Flag: per_run ->name: " . Flag::per_class->name . "
"; +print "Flag: per_run ->value: " . Flag::per_class->value . "
"; + +print "DUMP: " . $log->dV(['something' => 'error']) . "
"; + +$log->debug('LEGACY', 'Some legacy shit here'); +$log->debug('ARRAY', 'Dump some data: ' . $log->dV(['something' => 'error'])); +$log->debug('MIXED', 'Dump mixed: ' . $log->dV(<<block +and > and < +EOM)); +$log->info('Info message', ['info' => 'log']); +$log->error('Cannot process data', ['error' => 'log']); + +print "Log File: " . $log->getLogFile() . "
"; + +// init empty +unset($LOG_FILE_ID); +$ll = new CoreLibs\Logging\Logging([ + 'log_folder' => BASE . LOG, +]); +print "LFI: " . $ll->getLogFileId() . "
"; +try { + $ll->setLoggingLevel('Invalid'); +} catch (\Psr\Log\InvalidArgumentException $e) { + print "Invalid option: " . $e->getMessage() . "
"; +} +/* $ll = new CoreLibs\Logging\Logging([ + 'log_folder' => BASE . LOG, + 'log_file_id' => 'a', + 'log_file_id' => 'a', +]); */ + +print '
' + . '
' + // . '
'
+	. nl2br(htmlentities(file_get_contents($log->getLogFolder() . $log->getLogFile()) ?: ''))
+	// . '
' + . '
'; + +print ""; + +// __END__ diff --git a/www/admin/class_test.login.php b/www/admin/class_test.login.php index 6525561d..4da78948 100644 --- a/www/admin/class_test.login.php +++ b/www/admin/class_test.login.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -24,15 +19,10 @@ $LOG_FILE_ID = 'classTest-login'; $SET_SESSION_NAME = EDIT_SESSION_NAME; // init login & backend class $session = new CoreLibs\Create\Session($SET_SESSION_NAME); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $db = new CoreLibs\DB\IO(DB_CONFIG, $log); $login = new CoreLibs\ACL\Login( @@ -68,7 +58,4 @@ echo "ACL: " . \CoreLibs\Debug\Support::printAr($login->loginGetAcl()) . "
"; echo "ACL (MIN): " . \CoreLibs\Debug\Support::printAr($login->loginGetAcl()['min'] ?? []) . "
"; echo "LOCALE: " . \CoreLibs\Debug\Support::printAr($login->loginGetLocale()) . "
"; -// error message -print $log->printErrorMsg(); - print ""; diff --git a/www/admin/class_test.math.php b/www/admin/class_test.math.php index 7175c596..452af015 100644 --- a/www/admin/class_test.math.php +++ b/www/admin/class_test.math.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-math'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_math = new CoreLibs\Convert\Math(); $math_class = 'CoreLibs\Convert\Math'; @@ -57,9 +47,6 @@ print "S-INITNUMERIC: " . $math_class::initNumeric(123.456) . "
"; print "S-INITNUMERIC: " . $math_class::initNumeric('123') . "
"; print "S-INITNUMERIC: " . $math_class::initNumeric('123.456') . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.memoryusage.php b/www/admin/class_test.memoryusage.php index f178fa11..3c956ee0 100644 --- a/www/admin/class_test.memoryusage.php +++ b/www/admin/class_test.memoryusage.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Debug\MemoryUsage; use CoreLibs\Debug\Support; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: MEMORY USAGE'; @@ -81,9 +71,6 @@ print "Memory usage 4 array: " . Support::printAr($data) . "
"; print "Memory usage 4 string: " . MemoryUsage::printMemoryUsage($data) . "
"; print "Memory usage 4 string raw: " . MemoryUsage::printMemoryUsage($data, true) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.mime.php b/www/admin/class_test.mime.php index 798ddca7..079728b4 100644 --- a/www/admin/class_test.mime.php +++ b/www/admin/class_test.mime.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-mime'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_mime = new CoreLibs\Convert\MimeAppName(); @@ -60,8 +50,6 @@ print "S::App for mime $mime: " . \CoreLibs\Convert\MimeAppName::mimeGetAppName( $mime = 'application/vnd.ms-excel'; print "S::App for mime $mime: " . \CoreLibs\Convert\MimeAppName::mimeGetAppName($mime) . "
"; -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.output.form.php b/www/admin/class_test.output.form.php index 0a6d5c9d..44d9f8be 100644 --- a/www/admin/class_test.output.form.php +++ b/www/admin/class_test.output.form.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -55,15 +50,10 @@ $table_arrays[\CoreLibs\Get\System::getPageName(1)] = [ ] ]; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $l10n = new CoreLibs\Language\L10n( SITE_LOCALE, @@ -93,9 +83,6 @@ print "MOBILE PHONE: " . $form->mobile_phone . "
"; // sets table array to include print "MY PAGE NAME: " . $form->my_page_name . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.password.php b/www/admin/class_test.password.php index 3ca8e668..1211ed1b 100644 --- a/www/admin/class_test.password.php +++ b/www/admin/class_test.password.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Security\Password as PwdChk; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_password = new CoreLibs\Security\Password(); $password_class = 'CoreLibs\Security\Password'; @@ -61,9 +51,6 @@ print "PASSWORD REHASH: " . (string)$password_class::passwordRehashCheck($enc_pa // direct static print "S::PASSWORD VERFIY: " . (string)PwdChk::passwordVerify($password, $enc_password) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.php b/www/admin/class_test.php index e4c020ca..cd3f45e3 100644 --- a/www/admin/class_test.php +++ b/www/admin/class_test.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,17 +18,16 @@ require 'config.php'; $LOG_FILE_ID = 'classTest'; $SET_SESSION_NAME = EDIT_SESSION_NAME; +use CoreLibs\Logging; +use CoreLibs\Debug\Support; + // init login & backend class $session = new CoreLibs\Create\Session($SET_SESSION_NAME); -$log = new CoreLibs\Debug\Logging([ +$log = new Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, + 'log_file_id' => $LOG_FILE_ID, // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_per_date' => true, ]); $db = new CoreLibs\DB\IO(DB_CONFIG, $log); $login = new CoreLibs\ACL\Login( @@ -102,6 +96,7 @@ print ''; print ''; print ''; +print ''; print ''; print ''; print ''; @@ -116,10 +111,10 @@ print '
Class Test: CONFIG DIRECT print ''; print "
"; -print "L: " . CoreLibs\Debug\Support::printAr($locale) . "
"; +print "L: " . Support::dumpVar($locale) . "
"; // print all _ENV vars set print "
READ _ENV ARRAY:
"; -print CoreLibs\Debug\Support::printAr(array_map('htmlentities', $_ENV)); +print Support::dumpVar(array_map('htmlentities', $_ENV)); // set + check edit access id $edit_access_id = 3; if (is_object($login) && isset($login->loginGetAcl()['unit'])) { @@ -134,7 +129,7 @@ if (is_object($login) && isset($login->loginGetAcl()['unit'])) { print "Something went wrong with the login
"; } -// $backend->log->debug('SESSION', \CoreLibs\Debug\Support::printAr($_SESSION)); +// $backend->log->debug('SESSION', \CoreLibs\Debug\Support::dumpVar($_SESSION)); print '
'; print ''; print ''; -// print the debug core vars -foreach (['on', 'off'] as $flag) { - foreach (['debug', 'echo', 'print'] as $type) { - $prefix = $flag == 'off' ? 'NOT ' : ''; - print $prefix . strtoupper($type) . ' OUT: ' - . \CoreLibs\Debug\Support::printAr(\CoreLibs\Convert\SetVarType::setArray( - $backend->log->getLogLevel($type, $flag) - )) . '
'; - } -} -foreach (['debug', 'echo', 'print'] as $type) { - print strtoupper($type) . ' OUT ALL: ' . $backend->log->getLogLevelAll($type) . '
'; +print "Log Level: " . $backend->log->getLoggingLevel()->getName() . "
"; +print "Log ID: " . $backend->log->getLogFileId() . "
"; +print "Log Date: " . $backend->log->getLogDate() . "
"; +print "Log Max File Size: " . $backend->log->getLogMaxFileSize() . " bytes
"; +print "Log Flags: " . $backend->log->getLogFlags() . "
"; +foreach ( + [ + Logging\Logger\Flag::per_run, + Logging\Logger\Flag::per_date, + Logging\Logger\Flag::per_group, + Logging\Logger\Flag::per_page, + Logging\Logger\Flag::per_class, + Logging\Logger\Flag::per_level + ] as $flag +) { + print "Log Flag: " . $flag->name . ": " + . CoreLibs\Debug\Support::printBool($backend->log->getLogFlag($flag)) . "
"; } $log->debug('SOME MARK', 'Some error output'); @@ -162,7 +162,7 @@ $log->debug('SOME MARK', 'Some error output'); print "EDIT ACCESS ID: " . $backend->edit_access_id . "
"; if (is_object($login)) { // print "ACL:
".$backend->print_ar($login->loginGetAcl())."
"; - $log->debug('ACL', "ACL: " . \CoreLibs\Debug\Support::printAr($login->loginGetAcl())); + $log->debug('ACL', "ACL: " . \CoreLibs\Debug\Support::dumpVar($login->loginGetAcl())); // print "DEFAULT ACL:
".$backend->print_ar($login->default_acl_list)."
"; // print "DEFAULT ACL:
".$backend->print_ar($login->default_acl_list)."
"; // $result = array_flip( @@ -184,15 +184,11 @@ print "THIS HOST: " . HOST_NAME . ", with PROTOCOL: " . HOST_PROTOCOL . " is run print "DIR: " . DIR . "
"; print "BASE: " . BASE . "
"; print "ROOT: " . ROOT . "
"; -print "HOST: " . HOST_NAME . " => DB HOST: " . DB_CONFIG_NAME . " => " . print_r(DB_CONFIG, true) . "
"; +print "HOST: " . HOST_NAME . " => DB HOST: " . DB_CONFIG_NAME . " => " . Support::dumpVar(DB_CONFIG) . "
"; print "DS is: " . DIRECTORY_SEPARATOR . "
"; print "SERVER HOST: " . $_SERVER['HTTP_HOST'] . "
"; -// print error messages -// print $login->log->printErrorMsg(); -print $log->printErrorMsg(); - print ""; # __END__ diff --git a/www/admin/class_test.phpv.php b/www/admin/class_test.phpv.php index 20014b61..9098325f 100644 --- a/www/admin/class_test.phpv.php +++ b/www/admin/class_test.phpv.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Check\PhpVersion; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_phpv = new CoreLibs\Check\PhpVersion(); $phpv_class = 'CoreLibs\Check\PhpVersion'; @@ -71,9 +61,6 @@ print "U-S::MIN: $min_version: " . (string)PhpVersion::checkPHPVersion($min_vers print "PHP_VERSION_ID: " . PHP_VERSION_ID . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.randomkey.php b/www/admin/class_test.randomkey.php index 5193374d..b60b6c96 100644 --- a/www/admin/class_test.randomkey.php +++ b/www/admin/class_test.randomkey.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Create\RandomKey; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $array_class = 'CoreLibs\Create\RandomKey'; @@ -56,9 +46,6 @@ print "S::RANDOMKEYGEN($key_lenght_long): " . RandomKey::randomKeyGen($key_lengh $_array = new CoreLibs\Create\RandomKey(); print "C->RANDOMKEYGEN(auto): " . $_array->randomKeyGen() . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.readenvfile.php b/www/admin/class_test.readenvfile.php index 408576b1..28d706c7 100644 --- a/www/admin/class_test.readenvfile.php +++ b/www/admin/class_test.readenvfile.php @@ -18,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-readEnvFile'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL ?? true, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL ?? true, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $ref_class = 'CoreLibs\Get\ReadEnvFile'; @@ -44,9 +39,6 @@ $status = \CoreLibs\Get\DotEnv::readEnvFile('.', 'test.env'); print "test.env: STATUS: " . $status . "
"; print "AFTER reading test.env file: " . \CoreLibs\Debug\Support::printAr($_ENV) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.runningtime.php b/www/admin/class_test.runningtime.php index 54220947..13f71ddf 100644 --- a/www/admin/class_test.runningtime.php +++ b/www/admin/class_test.runningtime.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ ob_end_flush(); use CoreLibs\Debug\RunningTime; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: RUNNING TIME'; @@ -62,9 +52,6 @@ RunningTime::hrRunningTime(); echo "TIMED 2 [hr]: " . RunningTime::hrRunningTime() . "
"; echo "TIMED 2 [hr-end]: " . RunningTime::hrRunningTimeFromStart() . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.session.php b/www/admin/class_test.session.php index 116cc11c..0f685e87 100644 --- a/www/admin/class_test.session.php +++ b/www/admin/class_test.session.php @@ -2,11 +2,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); /** @@ -45,15 +40,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-session'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); use CoreLibs\Create\Session; $session = new Session(); @@ -173,9 +163,6 @@ print "[BAD NAME] Current session name: " . $session->getSessionName() . "
"; print "[BAD NAME] Current session active: " . ($session->checkActiveSession() ? 'Yes' : 'No') . "
"; print "[BAD NAME] Current session status: " . getSessionStatusString($session->getSessionStatus()) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.session.read.php b/www/admin/class_test.session.read.php index 6a8700b8..ec40f7c7 100644 --- a/www/admin/class_test.session.read.php +++ b/www/admin/class_test.session.read.php @@ -2,11 +2,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); /** @@ -45,15 +40,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-session.read'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); use CoreLibs\Create\Session; $session = new Session(); @@ -100,9 +90,6 @@ print "[READ] Confirm " . $var . " is " . $value . ": " print "[ALL SESSION]: " . \CoreLibs\Debug\Support::printAr($_SESSION) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.smarty.php b/www/admin/class_test.smarty.php index 34f97687..0615f0d6 100644 --- a/www/admin/class_test.smarty.php +++ b/www/admin/class_test.smarty.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -25,15 +20,10 @@ $ECHO_ALL = true; $LOG_FILE_ID = 'classTest-smarty'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $l10n = new \CoreLibs\Language\L10n( SITE_LOCALE, @@ -62,7 +52,7 @@ print ""; print '
'; print '

' . $PAGE_NAME . '

'; -$smarty->DATA['JS_DEBUG'] = DEBUG; +$smarty->DATA['JS_DEBUG'] = $log->getJsDebug(); $smarty->MASTER_TEMPLATE_NAME = 'main_body.tpl'; $smarty->TEMPLATE_NAME = 'smarty_test.tpl'; $smarty->CSS_SPECIAL_TEMPLATE_NAME = 'smart_test.css'; @@ -160,9 +150,6 @@ $smarty->setSmartyVarsAdmin( $adm ); -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.strings.php b/www/admin/class_test.strings.php index ae302fa5..af5a949b 100644 --- a/www/admin/class_test.strings.php +++ b/www/admin/class_test.strings.php @@ -2,11 +2,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -19,15 +14,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-string'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $byte_class = 'CoreLibs\Convert\Strings'; @@ -76,9 +66,6 @@ foreach ($test_splits as $split) { print "$split with count: " . \CoreLibs\Convert\Strings::countSplitParts($split) . "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.system.php b/www/admin/class_test.system.php index fa92d68e..9ba32c1d 100644 --- a/www/admin/class_test.system.php +++ b/www/admin/class_test.system.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -26,15 +21,10 @@ ob_end_flush(); use CoreLibs\Get\System; use CoreLibs\Debug\Support as DgS; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: SYSTEM'; @@ -61,7 +51,4 @@ print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): " print "System::checkCLI():
"; print "Are we in an CLI: " . (System::checkCLI() ? 'Yes' : 'No') . "
"; -// error message -print $log->printErrorMsg(); - print ""; diff --git a/www/admin/class_test.token.php b/www/admin/class_test.token.php index 38c5f9da..d6018876 100644 --- a/www/admin/class_test.token.php +++ b/www/admin/class_test.token.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-token'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_token = new CoreLibs\Output\Form\Token(); $token_class = 'CoreLibs\Output\Form\Token'; @@ -59,9 +49,6 @@ $token_id = $basic->setFormToken($token); print "TOKEN: $token: (ID) ".$token_id." => (S) ".$_SESSION[$token]."
"; print "VALIDATE: $token: ".(string)$basic->validateFormToken($token_id, $token)."
"; */ -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.uids.php b/www/admin/class_test.uids.php index 04162765..9aef4bdf 100644 --- a/www/admin/class_test.uids.php +++ b/www/admin/class_test.uids.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require 'config.php'; $LOG_FILE_ID = 'classTest-uids'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $_uids = new CoreLibs\Create\Uids(); use CoreLibs\Create\Uids; @@ -62,9 +52,6 @@ print "UNIQU ID LONG : " . Uids::uniqIdLong() . "
"; /* print "D/UUIDV4: ".$basic->uuidv4()."
"; print "/DUNIQID (d): ".$basic->uniqId()."
"; */ -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/class_test.varistype.php b/www/admin/class_test.varistype.php index 9ea875ff..cff5db49 100644 --- a/www/admin/class_test.varistype.php +++ b/www/admin/class_test.varistype.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -27,15 +22,10 @@ use CoreLibs\Convert\SetVarType; use CoreLibs\Convert\SetVarTypeNull; use CoreLibs\Debug\Support; -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: CONVERT\VARISTYPE'; @@ -109,9 +99,6 @@ foreach ($checks as $string) { print "
"; } -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/error_test.php b/www/admin/error_test.php index 02e2c0dc..ed3640db 100644 --- a/www/admin/error_test.php +++ b/www/admin/error_test.php @@ -2,12 +2,9 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = 1; -$PRINT_ALL = 1; -$DB_DEBUG = 1; +$DEBUG_LEVEL = \CoreLibs\Logging\Logger\Level::Debug; -if ($DEBUG_ALL) { +if ($DEBUG_LEVEL->name == 'Debug') { error_reporting(E_ALL); } diff --git a/www/admin/subfolder/class_test.config.direct.php b/www/admin/subfolder/class_test.config.direct.php index 3b9bcbf8..577b364d 100644 --- a/www/admin/subfolder/class_test.config.direct.php +++ b/www/admin/subfolder/class_test.config.direct.php @@ -6,11 +6,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = 1; -$PRINT_ALL = 1; -$DB_DEBUG = 1; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ require '../../configs/config.php'; $LOG_FILE_ID = 'classTest-config-direct'; ob_end_flush(); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $PAGE_NAME = 'TEST CLASS: CONFIG DIRECT SUB'; @@ -49,9 +39,6 @@ echo "Config path prefix: " . ($CONFIG_PATH_PREFIX ?? '') . "
"; print "DB Name: " . DB_CONFIG_NAME . "
"; print "DB Config: " . \CoreLibs\Debug\Support::printAr(DB_CONFIG) . "
"; -// error message -print $log->printErrorMsg(); - print ""; // __END__ diff --git a/www/admin/test_edit_base.php b/www/admin/test_edit_base.php index eb429e6d..b690eb6f 100644 --- a/www/admin/test_edit_base.php +++ b/www/admin/test_edit_base.php @@ -4,11 +4,6 @@ declare(strict_types=1); -$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations -$DEBUG_ALL = true; -$PRINT_ALL = true; -$DB_DEBUG = true; - error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); ob_start(); @@ -23,15 +18,10 @@ $SET_SESSION_NAME = EDIT_SESSION_NAME; // init login & backend class $session = new CoreLibs\Create\Session($SET_SESSION_NAME); -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - // add file date - 'print_file_date' => true, - // set debug and print flags - 'debug_all' => $DEBUG_ALL, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL, + 'log_file_id' => $LOG_FILE_ID, + 'log_per_date' => true, ]); $db = new CoreLibs\DB\IO(DB_CONFIG, $log); $login = new CoreLibs\ACL\Login( diff --git a/www/configs/config.host.php b/www/configs/config.host.php index 63ebde03..aa1c3eec 100644 --- a/www/configs/config.host.php +++ b/www/configs/config.host.php @@ -26,7 +26,7 @@ declare(strict_types=1); $__LOCAL_CONFIG = [ 'db_host' => 'test', 'location' => 'test', - 'debug_flag' => true, + 'debug_level' => 'debug', 'site_locale' => 'en_US.UTF-8', 'site_encoding' => 'UTF-8', 'login_enabled' => true @@ -44,7 +44,7 @@ $SITE_CONFIG = [ // location flagging (test/dev/live) for debug output 'location' => 'test', // show DEBUG override - 'debug_flag' => true, + 'debug_level' => 'debug', // site locale 'site_locale' => 'en_US.UTF-8', // site encoding diff --git a/www/configs/config.master.php b/www/configs/config.master.php index 51ed8267..17c174b5 100644 --- a/www/configs/config.master.php +++ b/www/configs/config.master.php @@ -140,13 +140,6 @@ define('DEFAULT_LOCALE', 'en_US.UTF-8'); // default web page encoding setting define('DEFAULT_ENCODING', 'UTF-8'); -/************* LOGGING *******************/ -// below two can be defined here, but they should be -// defined in either the header file or the file itself -// as $LOG_FILE_ID which takes presence over LOG_FILE_ID -// see Basic class constructor -define('LOG_FILE_ID', BASE_NAME); - /************* QUEUE TABLE *************/ // if we have a dev/live system // set_live is a per page/per item @@ -241,7 +234,7 @@ $GLOBALS['DB_CONFIG_SET'] = DB_CONFIG; // define('GLOBAL_DB_SCHEMA', PUBLIC_SCHEMA); // debug settings, site lang, etc define('TARGET', $SITE_CONFIG[HOST_NAME]['location'] ?? 'test'); -define('DEBUG', $SITE_CONFIG[HOST_NAME]['debug_flag'] ?? false); +define('DEBUG_LEVEL', $SITE_CONFIG[HOST_NAME]['debug_level'] ?? 'debug'); define('SITE_LOCALE', $SITE_CONFIG[HOST_NAME]['site_locale'] ?? DEFAULT_LOCALE); define('SITE_DOMAIN', str_replace(DIRECTORY_SEPARATOR, '', CONTENT_PATH)); define('SITE_ENCODING', $SITE_CONFIG[HOST_NAME]['site_encoding'] ?? DEFAULT_ENCODING); @@ -252,9 +245,6 @@ define('AUTH', $SITE_CONFIG[HOST_NAME]['auth'] ?? false); // define('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin'] ?? ''); // define('REDIRECT_URL', $PATHS[TARGET]['redirect_url'] ?? ''); -// show all errors if debug_all & show_error_handling are enabled -define('SHOW_ALL_ERRORS', true); - /************* GENERAL PAGE TITLE ********/ define('G_TITLE', $_ENV['G_TITLE'] ?? ''); @@ -271,22 +261,4 @@ if (file_exists(BASE . CONFIGS . 'config.other.php')) { require BASE . CONFIGS . 'config.other.php'; } -/************* DEBUG *******************/ -// turn off debug if debug flag is OFF -if (defined('DEBUG') && DEBUG == false) { - $ECHO_ALL = false; - $DEBUG_ALL = false; - $PRINT_ALL = false; - $DB_DEBUG = false; - $ENABLE_ERROR_HANDLING = false; - $DEBUG_ALL_OVERRIDE = false; -} else { - $ECHO_ALL = false; - $DEBUG_ALL = true; - $PRINT_ALL = true; - $DB_DEBUG = true; - $ENABLE_ERROR_HANDLING = false; - $DEBUG_ALL_OVERRIDE = false; -} - // __END__ diff --git a/www/includes/admin_header.php b/www/includes/admin_header.php index 7ba8f52f..6c920790 100644 --- a/www/includes/admin_header.php +++ b/www/includes/admin_header.php @@ -51,25 +51,16 @@ if ($AJAX_PAGE && !$ZIP_STREAM) { // start session $session = new \CoreLibs\Create\Session($SET_SESSION_NAME); // create logger -$log = new \CoreLibs\Debug\Logging([ +$log = new \CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => $LOG_FILE_ID, - 'print_file_date' => true, - 'debug_all' => $DEBUG_ALL ?? false, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL ?? false, + 'log_file_id' => $LOG_FILE_ID, + // set log level based on host setting + 'log_level' => \CoreLibs\Logging\Logging::processLogLevel(DEBUG_LEVEL), + 'log_per_date' => true, ]); -// automatic hide for DEBUG messages on live server -// can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script -// (for emergency debugging of one page only) -if ( - (TARGET == 'live' || TARGET == 'remote') && - DEBUG === true && - !empty($DEBUG_ALL_OVERRIDE) -) { - foreach (['debug', 'echo', 'print'] as $target) { - $log->setLogLevelAll($target, false); - } +// allow override of debug log level settings +if (!empty($DEBUG_ALL_OVERRIDE)) { + $log->setLoggingLevel((string)$DEBUG_ALL_OVERRIDE); } // db config with logger $db = new \CoreLibs\DB\IO(DB_CONFIG, $log); @@ -130,6 +121,6 @@ if (!$login->loginActionRun()) { //------------------------------ logging end // pass on DEBUG flag to JS via smarty variable -$smarty->DATA['JS_DEBUG'] = DEBUG; +$smarty->DATA['JS_DEBUG'] = $log->getJsDebug(); // __END__ diff --git a/www/includes/edit_base.php b/www/includes/edit_base.php index 3b22b2b8..0278845b 100644 --- a/www/includes/edit_base.php +++ b/www/includes/edit_base.php @@ -31,14 +31,11 @@ header("Content-type: text/html; charset=" . DEFAULT_ENCODING); // start session $session = new \CoreLibs\Create\Session(EDIT_SESSION_NAME); // init logger -$log = new CoreLibs\Debug\Logging([ +$log = new CoreLibs\Logging\Logging([ 'log_folder' => BASE . LOG, - 'file_id' => LOG_FILE_ID . 'EditBase', - 'print_file_date' => true, - 'per_class' => true, - 'debug_all' => $DEBUG_ALL ?? false, - 'echo_all' => $ECHO_ALL ?? false, - 'print_all' => $PRINT_ALL ?? false, + 'log_file_id' => BASE_NAME . 'EditBase', + 'log_per_date' => true, + 'log_per_class' => true, ]); // db connection $db = new CoreLibs\DB\IO(DB_CONFIG, $log); diff --git a/www/lib/CoreLibs/ACL/Login.php b/www/lib/CoreLibs/ACL/Login.php index e657ee19..b2037472 100644 --- a/www/lib/CoreLibs/ACL/Login.php +++ b/www/lib/CoreLibs/ACL/Login.php @@ -204,7 +204,7 @@ class Login 'path' => '', ]; - /** @var \CoreLibs\Debug\Logging logger */ + /** @var \CoreLibs\Logging\Logging logger */ public $log; /** @var \CoreLibs\DB\IO database */ public $db; @@ -218,21 +218,21 @@ class Login * finishes itself * * @param \CoreLibs\DB\IO $db Database connection class - * @param \CoreLibs\Debug\Logging $log Logging class + * @param \CoreLibs\Logging\Logging $log Logging class * @param \CoreLibs\Create\Session $session Session interface class * @param array $options Login ACL settings * $auto_login [default true] DEPRECATED, moved into options */ public function __construct( \CoreLibs\DB\IO $db, - \CoreLibs\Debug\Logging $log, + \CoreLibs\Logging\Logging $log, \CoreLibs\Create\Session $session, array $options = [] ) { // attach db class $this->db = $db; // log login data for this class only - $log->setLogPer('class', true); + $log->setLogFlag(\CoreLibs\Logging\Logger\Flag::per_class); // attach logger $this->log = $log; // attach session class @@ -1179,6 +1179,12 @@ class Login $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; } + $this->acl['unit_id'] = null; + $this->acl['unit_name'] = null; + $this->acl['unit_uid'] = null; + $this->acl['unit'] = []; + $this->acl['unit_detail'] = []; + // PER ACCOUNT (UNIT/edit access)-> foreach ($_SESSION['UNIT'] as $ea_id => $unit) { // if admin flag is set, all units are set to 100 @@ -1911,21 +1917,6 @@ HTML; // echo $this->login_html; $this->loginPrintLogin(); } - // do not go anywhere, quit processing here - // do something with possible debug data? - if ( - in_array($this->options['target'], ['live', 'remove']) - ) { - // login - $this->log->setLogLevelAll('debug', $this->options['debug']); - $this->log->setLogLevelAll('echo', false); - $this->log->setLogLevelAll('print', $this->options['debug']); - } - $status_msg = $this->log->printErrorMsg(); - // if ($this->echo_output_all) { - if ($this->log->getLogLevelAll('echo')) { - echo $status_msg; - } // exit so we don't process anything further, at all $this->loginTerminate(3000); } else { diff --git a/www/lib/CoreLibs/Admin/Backend.php b/www/lib/CoreLibs/Admin/Backend.php index 2ea48041..09ab6a39 100644 --- a/www/lib/CoreLibs/Admin/Backend.php +++ b/www/lib/CoreLibs/Admin/Backend.php @@ -95,7 +95,7 @@ class Backend public $domain; /** @var string */ public $encoding; - /** @var \CoreLibs\Debug\Logging logger */ + /** @var \CoreLibs\Logging\Logging logger */ public $log; /** @var \CoreLibs\DB\IO database */ public $db; @@ -118,14 +118,14 @@ class Backend * main class constructor * * @param \CoreLibs\DB\IO $db Database connection class - * @param \CoreLibs\Debug\Logging $log Logging class + * @param \CoreLibs\Logging\Logging $log Logging class * @param \CoreLibs\Create\Session $session Session interface class * @param \CoreLibs\Language\L10n $l10n l10n language class * @param int|null $set_default_acl_level Default ACL level */ public function __construct( \CoreLibs\DB\IO $db, - \CoreLibs\Debug\Logging $log, + \CoreLibs\Logging\Logging $log, \CoreLibs\Create\Session $session, \CoreLibs\Language\L10n $l10n, ?int $set_default_acl_level = null @@ -133,7 +133,7 @@ class Backend // attach db class $this->db = $db; // set to log not per class - $log->setLogPer('class', false); + $log->unsetLogFlag(\CoreLibs\Logging\Logger\Flag::per_class); // attach logger $this->log = $log; // attach session class diff --git a/www/lib/CoreLibs/Admin/EditBase.php b/www/lib/CoreLibs/Admin/EditBase.php index 3933d535..6610c1df 100644 --- a/www/lib/CoreLibs/Admin/EditBase.php +++ b/www/lib/CoreLibs/Admin/EditBase.php @@ -33,7 +33,7 @@ class EditBase private $smarty; /** @var \CoreLibs\Output\Form\Generate form generate system */ private $form; - /** @var \CoreLibs\Debug\Logging */ + /** @var \CoreLibs\Logging\Logging */ public $log; /** @var \CoreLibs\ACL\Login */ public $login; @@ -42,14 +42,14 @@ class EditBase * construct form generator * * @param array $db_config db config array, mandatory - * @param \CoreLibs\Debug\Logging $log Logging class, null auto set + * @param \CoreLibs\Logging\Logging $log Logging class, null auto set * @param \CoreLibs\Language\L10n $l10n l10n language class, null auto set * @param \CoreLibs\ACL\Login $login login class for ACL settings * @param array $options Various settings options */ public function __construct( array $db_config, - \CoreLibs\Debug\Logging $log, + \CoreLibs\Logging\Logging $log, \CoreLibs\Language\L10n $l10n, \CoreLibs\ACL\Login $login, array $options @@ -63,7 +63,7 @@ class EditBase $options['compile_id'] ?? '', ); // turn off set log per class - $log->setLogPer('class', false); + $log->unsetLogFlag(\CoreLibs\Logging\Logger\Flag::per_class); // create form class $this->form = new \CoreLibs\Output\Form\Generate( diff --git a/www/lib/CoreLibs/Basic.php b/www/lib/CoreLibs/Basic.php index 7e1882e8..5d291b8f 100644 --- a/www/lib/CoreLibs/Basic.php +++ b/www/lib/CoreLibs/Basic.php @@ -64,7 +64,7 @@ class Basic /** @var int */ public $host_port; // logging interface, Debug\Logging class - /** @var \CoreLibs\Debug\Logging */ + /** @var \CoreLibs\Logging\Logging */ public $log; /** @var \CoreLibs\Create\Session */ public $session; @@ -85,12 +85,12 @@ class Basic /** * main Basic constructor to init and check base settings - * @param \CoreLibs\Debug\Logging|null $log Logging class + * @param \CoreLibs\Logging\Logging|null $log Logging class * @param string|null $session_name Set session name * @deprecated DO NOT USE Class\Basic anymore. Use dedicated logger and sub classes */ public function __construct( - \CoreLibs\Debug\Logging $log = null, + \CoreLibs\Logging\Logging $log = null, ?string $session_name = null ) { trigger_error('Class \CoreLibs\Basic is deprected', E_USER_DEPRECATED); @@ -120,7 +120,10 @@ class Basic } // logging interface moved here (->debug is now ->log->debug) - $this->log = $log ?? new \CoreLibs\Debug\Logging(); + $this->log = $log ?? new \CoreLibs\Logging\Logging([ + 'log_folder' => BASE . LOG, + 'log_file_id' => 'ClassBasic-DEPRECATED', + ]); // set ajax page flag based on the AJAX_PAGE varaibles // convert to true/false so if AJAX_PAGE is 0 or false it is @@ -176,8 +179,9 @@ class Basic */ public function basicSetLogId(string $string): string { - trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->basicSetLogId() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); - return $this->log->setLogId($string); + trigger_error('Method ' . __METHOD__ . ' is deprecated, use log->setLogId() or use \CoreLibs\Logging\Logging() class', E_USER_DEPRECATED); + $this->log->setLogFileId($string); + return $this->log->getLogFileId(); } // ****** DEBUG/ERROR FUNCTIONS ****** @@ -252,7 +256,7 @@ class Basic } // ****** DEBUG LOGGING FUNCTIONS ****** - // Moved to \CoreLibs\Debug\Logging + // Moved to \CoreLibs\Logging\Logging /** * passes list of level names, to turn on debug @@ -265,68 +269,9 @@ class Basic */ public function debugFor(string $type, string $flag): void { - trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->debugFor() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); - /** @phan-suppress-next-line PhanTypeMismatchArgumentReal, PhanParamTooFew @phpstan-ignore-next-line */ - $this->log->setLogLevel(...[func_get_args()]); + trigger_error('Method ' . __METHOD__ . ' functionaility is fully deprecated', E_USER_DEPRECATED); } - /** - * checks if we have a need to work on certain debug output - * Needs debug/echo/print ad target for which of the debug flag groups we check - * also needs level string to check in the per level output flag check. - * In case we have invalid target it will return false - * @param string $target target group to check debug/echo/print - * @param string $level level to check in detailed level flag - * @return bool true on access allowed or false on no access - */ - /* private function doDebugTrigger(string $target, string $level): bool - { - $access = false; - // check if we do debug, echo or print - switch ($target) { - case 'debug': - if (( - (isset($this->debug_output[$level]) && $this->debug_output[$level]) || - $this->debug_output_all - ) && - (!isset($this->debug_output_not[$level]) || - (isset($this->debug_output_not[$level]) && !$this->debug_output_not[$level]) - ) - ) { - $access = true; - } - break; - case 'echo': - if (( - (isset($this->echo_output[$level]) && $this->echo_output[$level]) || - $this->echo_output_all - ) && - (!isset($this->echo_output_not[$level]) || - (isset($this->echo_output_not[$level]) && !$this->echo_output_not[$level]) - ) - ) { - $access = true; - } - break; - case 'print': - if (( - (isset($this->print_output[$level]) && $this->print_output[$level]) || - $this->print_output_all - ) && - (!isset($this->print_output_not[$level]) || - (isset($this->print_output_not[$level]) && !$this->print_output_not[$level]) - ) - ) { - $access = true; - } - break; - default: - // fall through with access false - break; - } - return $access; - } */ - /** * write debug data to error_msg array * @param string $level id for error message, groups messages together @@ -335,11 +280,12 @@ class Basic * all html tags will be stripped and
changed to \n * this is only used for debug output * @return void has no return - * @deprecated Use $basic->log->debug() instead + * @deprecated Use Logger\Logger->debug() instead */ public function debug(string $level, string $string, bool $strip = false): void { - $this->log->debug($level, $string, $strip); + trigger_error('Method ' . __METHOD__ . ' has moved to Logger\Logger->debug()', E_USER_DEPRECATED); + $this->log->debug($level, $string); } /** @@ -351,8 +297,7 @@ class Basic */ public function mergeErrors(array $error_msg = []): void { - trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->mergeErrors() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); - $this->log->mergeErrors($error_msg); + trigger_error('Method ' . __METHOD__ . ' is fully deprecated', E_USER_DEPRECATED); } /** @@ -363,7 +308,8 @@ class Basic */ public function printErrorMsg(string $string = ''): string { - return $this->log->printErrorMsg($string); + trigger_error('Method ' . __METHOD__ . ' is fully deprecated', E_USER_DEPRECATED); + return ''; } /** @@ -376,8 +322,7 @@ class Basic */ public function resetErrorMsg(string $level = ''): void { - trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->resetErrorMsg() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); - $this->log->resetErrorMsg($level); + trigger_error('Method ' . __METHOD__ . ' is fully deprecated', E_USER_DEPRECATED); } // ****** DEBUG SUPPORT FUNCTIONS ****** @@ -388,11 +333,11 @@ class Basic * prints a html formatted (pre) array * @param array $array any array * @return string formatted array for output with
 tag added
-	 * @deprecated Use $this->log->prAr() instead
+	 * @deprecated Use \CoreLibs\Debug\Support::prAr() instead
 	 */
 	public function printAr(array $array): string
 	{
-		return $this->log->prAr($array);
+		return \CoreLibs\Debug\Support::prAr($array);
 	}
 
 	/**
diff --git a/www/lib/CoreLibs/Create/Email.php b/www/lib/CoreLibs/Create/Email.php
index def74379..702978ad 100644
--- a/www/lib/CoreLibs/Create/Email.php
+++ b/www/lib/CoreLibs/Create/Email.php
@@ -137,7 +137,7 @@ class Email
 	 * @param  bool                 $kv_folding      If set to true and a valid encoding,
 	 *                                               do KV folding
 	 * @param  bool                 $test            test flag, default off
-	 * @param  \CoreLibs\Debug\Logging|null $log     Logging class,
+	 * @param  \CoreLibs\Logging\Logging|null $log     Logging class,
 	 *                                               only used if test flag is true
 	 * @return int                  2 test only, no sent
 	 *                              1 for ok,
@@ -156,7 +156,7 @@ class Email
 		string $encoding = 'UTF-8',
 		bool $kv_folding = false,
 		bool $test = false,
-		?\CoreLibs\Debug\Logging $log = null
+		?\CoreLibs\Logging\Logging $log = null
 	): int {
 		/** @var array */
 		$to_emails = [];
@@ -259,11 +259,11 @@ class Email
 				$mail_delivery_status = 2;
 			}
 			// log if an log instance exists
-			if ($log instanceof \CoreLibs\Debug\Logging) {
+			if ($log instanceof \CoreLibs\Logging\Logging) {
 				// build debug strings: convert to UTF-8 if not utf-8
-				$log->debug('SEND EMAIL', 'HEADERS: ' . $log->prAr($headers) . ', '
+				$log->debug('SEND EMAIL', 'HEADERS: ' . \CoreLibs\Debug\Support::prAr($headers) . ', '
 					. 'ENCODING: ' . $encoding . ',  '
-					. 'KV FOLDING: ' . $log->prBl($kv_folding) . ',  '
+					. 'KV FOLDING: ' . \CoreLibs\Debug\Support::prBl($kv_folding) . ',  '
 					. 'TO: ' . $to_email . ', '
 					. 'SUBJECT: ' . $out_subject . ', '
 					. 'BODY: ' . ($encoding == 'UTF-8' ?
diff --git a/www/lib/CoreLibs/DB/Extended/ArrayIO.php b/www/lib/CoreLibs/DB/Extended/ArrayIO.php
index 5abeac97..a3289693 100644
--- a/www/lib/CoreLibs/DB/Extended/ArrayIO.php
+++ b/www/lib/CoreLibs/DB/Extended/ArrayIO.php
@@ -57,7 +57,7 @@ class ArrayIO extends \CoreLibs\DB\IO
 	 * @param array $db_config      db connection config
 	 * @param array $table_array    table array config
 	 * @param string       $table_name     table name string
-	 * @param \CoreLibs\Debug\Logging $log Logging class
+	 * @param \CoreLibs\Logging\Logging $log Logging class
 	 * @param int          $base_acl_level Set base acl level, if needed
 	 * @param int          $acl_admin      Flag if this is an admin ACL access level
 	 */
@@ -65,7 +65,7 @@ class ArrayIO extends \CoreLibs\DB\IO
 		array $db_config,
 		array $table_array,
 		string $table_name,
-		\CoreLibs\Debug\Logging $log,
+		\CoreLibs\Logging\Logging $log,
 		int $base_acl_level = 0,
 		int $acl_admin = 0
 	) {
diff --git a/www/lib/CoreLibs/DB/IO.php b/www/lib/CoreLibs/DB/IO.php
index 6d0f1e5c..04a47339 100644
--- a/www/lib/CoreLibs/DB/IO.php
+++ b/www/lib/CoreLibs/DB/IO.php
@@ -391,18 +391,18 @@ class IO
 	/** @var string */
 	private $async_running;
 	// logging class, must be public so settings can be changed
-	/** @var \CoreLibs\Debug\Logging */
+	/** @var \CoreLibs\Logging\Logging */
 	public $log;
 
 	/**
 	 * main DB concstructor with auto connection to DB and failure set on failed connection
 	 * @param array $db_config DB configuration array
-	 * @param \CoreLibs\Debug\Logging $log Logging class
+	 * @param \CoreLibs\Logging\Logging $log Logging class
 	 * @param bool|null $db_debug_override Overrides debug settings in db_config
 	 */
 	public function __construct(
 		array $db_config,
-		\CoreLibs\Debug\Logging $log,
+		\CoreLibs\Logging\Logging $log,
 		?bool $db_debug_override = null
 	) {
 		// attach logger
@@ -703,10 +703,10 @@ class IO
 		}
 		if ($error_data !== []) {
 			$error_string .= '
[' - . $this->log->prAr($error_data) + . \CoreLibs\Debug\Support::prAr($error_data) . ']'; } - $this->log->debug($debug_id, $error_string, true, $prefix); + $this->log->debug($debug_id, $error_string, $prefix); } /** @@ -2737,7 +2737,7 @@ class IO if ($result === false) { $this->log->debug('ExecuteData', 'ERROR in STM[' . $stm_name . '|' . $this->prepare_cursor[$stm_name]['result'] . ']: ' - . $this->log->prAr($data)); + . \CoreLibs\Debug\Support::prAr($data)); $this->__dbError( 22, $this->prepare_cursor[$stm_name]['result'], diff --git a/www/lib/CoreLibs/Debug/Logging.php b/www/lib/CoreLibs/Debug/Logging.php index de4e710e..e961aab9 100644 --- a/www/lib/CoreLibs/Debug/Logging.php +++ b/www/lib/CoreLibs/Debug/Logging.php @@ -1,895 +1,26 @@ */ - private $options = []; - // page and host name - /** @var string */ - private $page_name; - /** @var string */ - private $host_name; - /** @var int */ - private $host_port; - // internal error reporting vars - /** @var array */ - private $error_msg = []; // the "connection" to the outside errors - // debug output prefix - /** @var string */ - private $error_msg_prefix = ''; // prefix to the error string (the class name) - // debug flags - /** @var array */ - private $debug_output = []; // if this is true, show debug on desconstructor - /** @var array */ - private $debug_output_not = []; - /** @var bool */ - private $debug_output_all = false; - /** @var array */ - private $echo_output = []; // errors: echo out, default is 1 - /** @var array */ - private $echo_output_not = []; - /** @var bool */ - private $echo_output_all = false; - /** @var array */ - private $print_output = []; // errors: print to file, default is 0 - /** @var array */ - private $print_output_not = []; - /** @var bool */ - private $print_output_all = false; - // debug flags/settings - /** @var string */ - private $running_uid = ''; // unique ID set on class init and used in logging as prefix - // log file name - /** @var string */ - private $log_folder = ''; - /** @var string */ - private $log_file_name_ext = 'log'; // use this for date rotate - /** @var string */ - private $log_file_name = ''; - /** @var int */ - private $log_max_filesize = 0; // set in kilobytes - /** @var string */ - private $log_print_file = 'error_msg##LOGID####LEVEL####CLASS####PAGENAME####DATE##'; - /** @var string */ - private $log_file_unique_id; // a unique ID set only once for call derived from this class - /** @var string */ - private $log_file_date = ''; // Y-m-d file in file name - /** @var bool */ - private $log_print_file_date = true; // if set add Y-m-d and do automatic daily rotation - /** @var string */ - private $log_file_id = ''; // a alphanumeric name that has to be set as global definition - /** @var bool */ - private $log_per_level = false; // set, it will split per level (first parameter in debug call) - /** @var bool */ - private $log_per_class = false; // set, will split log per class - /** @var bool */ - private $log_per_page = false; // set, will split log per called file - /** @var bool */ - private $log_per_run = false; // create a new log file per run (time stamp + unique ID) - // script running time - /** @var float */ - private $script_starttime; - /** - * Init logger - * - * global vars that can be used - * - BASE - * - LOG - * - LOG_FILE_ID - * options array layout - * - log_folder: - * - print_file_date: - * - file_id: - * - unique_id: - * - log_per_level: - * - log_per_class: - * - log_per_page: - * - log_per_run: - * - debug_all: - * - echo_all: - * - print_all: - * - debug (array): - * - echo (array): - * - print (array): - * - debug_not (array): - * - echo_not (array): - * - print_not (array): * * @param array $options Array with settings options */ public function __construct(array $options = []) { - // copy the options over - $this->options = $options; - // set log folder from options - $this->log_folder = $this->options['log_folder'] ?? ''; - // legacy flow, check must set constants - if (empty($this->log_folder) && defined('BASE') && defined('LOG')) { - /** @deprecated Do not use this anymore, define path on class load */ - trigger_error( - 'options: log_folder must be set. Setting via BASE and LOG constants is deprecated', - E_USER_DEPRECATED - ); - // make sure this is writeable, else skip - $this->log_folder = BASE . LOG; - } - // fallback + notice - if (empty($this->log_folder)) { - /* trigger_error( - 'options or constant not set or folder not writable. fallback to: ' . getcwd(), - E_USER_NOTICE - ); */ - $this->log_folder = getcwd() . DIRECTORY_SEPARATOR; - } - // if folder is not writeable, abort - if (!is_writeable($this->log_folder)) { - trigger_error( - 'Folder: ' . $this->log_folder . ' is not writeable for logging', - E_USER_ERROR - ); - } - // check if log_folder has a trailing / - if (substr($this->log_folder, -1, 1) != DIRECTORY_SEPARATOR) { - $this->log_folder .= DIRECTORY_SEPARATOR; - } - // running time start for script - $this->script_starttime = microtime(true); - // set per run UID for logging - $this->running_uid = Uids::uniqIdShort(); - // set the page name - $this->page_name = System::getPageName(); - // set host name - list($this->host_name , $this->host_port) = System::getHostName(); - // add port to host name if not port 80 - if ($this->host_port != 80) { - $this->host_name .= ':' . $this->host_port; - } - - // can be overridden with basicSetLogFileId later - if (!empty($this->options['file_id'])) { - $this->setLogId($this->options['file_id']); - } elseif (!empty($GLOBALS['LOG_FILE_ID'])) { - /** @deprecated Do not use this anymore, define file_id on class load */ - trigger_error( - 'options: file_id must be set. Setting via LOG_FILE_ID global variable is deprecated', - E_USER_DEPRECATED - ); - // legacy flow, should be removed and only set via options - $this->setLogId($GLOBALS['LOG_FILE_ID']); - // TODO trigger deprecation error - // trigger_error( - // 'Debug\Logging: Do not use globals LOG_FILE_ID to set log id for Logging', - // E_USER_DEPRECATED - // ); - } elseif (defined('LOG_FILE_ID')) { - /** @deprecated Do not use this anymore, define file_id on class load */ - trigger_error( - 'options: file_id must be set. Setting via LOG_FILE_ID constant is deprecated', - E_USER_DEPRECATED - ); - // legacy flow, should be removed and only set via options - $this->setLogId(LOG_FILE_ID); - // trigger deprecation error - // trigger_error( - // 'Debug\Logging: Do not use constant LOG_FILE_ID to set log id for Logging', - // E_USER_DEPRECATED - // ); - } - - // init the log levels - $this->initLogLevels(); - } - - // *** PRIVATE *** - - /** - * init the basic log levels based on global set variables - * - * @return void - */ - private function initLogLevels(): void - { - // if given via parameters, only for all - // globals overrule given settings, for one (array), eg $ECHO['db'] = 1; - foreach (['debug', 'echo', 'print'] as $type) { - // include or exclude (off) from output - foreach (['on', 'off'] as $flag) { - $in_type = $type; - if ($flag == 'off') { - $in_type .= '_not'; - } - $up_type = strtoupper($in_type); - if ( - isset($this->options[$in_type]) && - is_array($this->options[$in_type]) - ) { - $this->setLogLevel($type, $flag, $this->options[$in_type]); - } elseif ( - isset($GLOBALS[$up_type]) && - is_array($GLOBALS[$up_type]) - ) { - // TODO trigger deprecation error - $this->setLogLevel($type, $flag, $GLOBALS[$up_type]); - } - } - } - - // TODO remove all $GLOBALS call and only use options - // all overrule - $this->setLogLevelAll( - 'debug', - $this->options['debug_all'] ?? - // for user login, should be handled outside like globals - $_SESSION['DEBUG_ALL'] ?? // DEPRECATED - $GLOBALS['DEBUG_ALL'] ?? // DEPRECATED - false - ); - $this->setLogLevelAll( - 'print', - $this->options['print_all'] ?? - // for user login, should be handled outside like globals - $_SESSION['DEBUG_ALL'] ?? // DEPRECATED - $GLOBALS['PRINT_ALL'] ?? // DEPRECATED - false - ); - $this->setLogLevelAll( - 'echo', - $this->options['echo_all'] ?? - $GLOBALS['ECHO_ALL'] ?? // DEPRECATED - false - ); - - // GLOBAL rules for log writing - // add file date is default on - $this->setGetLogPrintFileDate( - $this->options['print_file_date'] ?? - $GLOBALS['LOG_PRINT_FILE_DATE'] ?? // DEPRECATED - true - ); - // all other logging file name flags are off - $this->setLogPer( - 'level', - $this->options['per_level'] ?? - $GLOBALS['LOG_PER_LEVEL'] ?? // DEPRECATED - false - ); - $this->setLogPer( - 'class', - $this->options['per_class'] ?? - $GLOBALS['LOG_PER_CLASS'] ?? // DEPRECATED - false - ); - $this->setLogPer( - 'page', - $this->options['per_page'] ?? - $GLOBALS['LOG_PER_PAGE'] ?? // DEPRECATED - false - ); - $this->setLogPer( - 'run', - $this->options['per_run'] ?? - $GLOBALS['LOG_PER_RUN'] ?? // DEPRECATED - false - ); - // set log per date - if ($this->setGetLogPrintFileDate()) { - $this->log_file_date = date('Y-m-d'); - } - // set per run ID - if ($this->log_per_run) { - $this->setLogUniqueId(); - } - } - - /** - * checks if we have a need to work on certain debug output - * Needs debug/echo/print ad target for which of the debug flag groups we check - * also needs level string to check in the per level output flag check. - * In case we have invalid target it will return false - * - * @param string $target target group to check debug/echo/print - * @param string $level level to check in detailed level flag - * @return bool true on access allowed or false on no access - */ - private function doDebugTrigger(string $target, string $level): bool - { - $access = false; - // check if we do debug, echo or print - if ( - ( - $this->getLogLevel($target, 'on', $level) || - $this->getLogLevelAll($target) - ) && - !$this->getLogLevel($target, 'off', $level) - ) { - $access = true; - } - return $access; - } - - /** - * writes error msg data to file for current level - * - * @param string $level the level to write - * @param string $error_string error string to write - * @return bool True if message written, FAlse if not - */ - private function writeErrorMsg(string $level, string $error_string): bool - { - // only write if write is requested - if ( - !($this->doDebugTrigger('debug', $level) && - $this->doDebugTrigger('print', $level)) - ) { - return false; - } - - // init base file path - $fn = $this->log_folder . $this->log_print_file . '.' . $this->log_file_name_ext; - // log ID prefix settings, if not valid, replace with empty - if (!empty($this->log_file_id)) { - $rpl_string = '_' . $this->log_file_id; - } else { - $rpl_string = ''; - } - $fn = str_replace('##LOGID##', $rpl_string, $fn); // log id (like a log file prefix) - - if ($this->log_per_run) { - $rpl_string = '_' . $this->log_file_unique_id; // add 8 char unique string - } elseif ($this->setGetLogPrintFileDate()) { - $rpl_string = '_' . $this->log_file_date; // add date to file - } else { - $rpl_string = ''; - } - $fn = str_replace('##DATE##', $rpl_string, $fn); // create output filename - - // write per level - $rpl_string = !$this->log_per_level ? '' : - // normalize level, replace all non alphanumeric characters with - - '_' . ( - // if return is only - then set error string - preg_match( - "/^-+$/", - $level_string = preg_replace("/[^A-Za-z0-9-_]/", '-', $level) ?? '' - ) ? - 'INVALID-LEVEL-STRING' : - $level_string - ); - $fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename - // set per class, but don't use get_class as we will only get self - $rpl_string = !$this->log_per_class ? '' : '_' - // set sub class settings - . str_replace('\\', '-', Support::getCallerClass()); - $fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename - - // if request to write to one file - $rpl_string = !$this->log_per_page ? - '' : - '_' . System::getPageName(System::NO_EXTENSION); - $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename - - // write to file - // first check if max file size is is set and file is bigger - if ( - $this->log_max_filesize > 0 && - ((filesize($fn) / 1024) > $this->log_max_filesize) - ) { - // for easy purpose, rename file only to attach timestamp, nur sequence numbering - rename($fn, $fn . '.' . date("YmdHis")); - } - $this->log_file_name = $fn; - $fp = fopen($this->log_file_name, 'a'); - if ($fp !== false) { - fwrite($fp, $error_string); - fclose($fp); - return true; - } else { - echo ""; - return false; - } - } - - // *** PUBLIC *** - - /** - * Temporary method to read all class variables for testing purpose - * - * @param string $name what variable to return - * @return mixed can be anything, bool, string, int, array - */ - public function getSetting(string $name): mixed - { - // for debug purpose only - return $this->{$name}; - } - - /** - * sets the internal log file prefix id - * string must be a alphanumeric string - * if non valid string is given it returns the previous set one only - * - * @param string $string log file id string value - * @return string returns the set log file id string - * @deprecated Use $log->setLogId() - */ - public function basicSetLogId(string $string): string - { - return $this->setLogId($string); - } - - /** - * sets the internal log file prefix id - * string must be a alphanumeric string - * if non valid string is given it returns the previous set one only - * - * @param string $string log file id string value - * @return string returns the set log file id string - */ - public function setLogId(string $string): string - { - if (preg_match("/^[\w\-]+$/", $string)) { - $this->log_file_id = $string; - } - return $this->log_file_id; - } - - /** - * return current set log file id - * @return string - */ - public function getLogId(): string - { - return $this->log_file_id; - } - - /** - * old name for setLogLevel - * - * @param string $type debug, echo, print - * @param string $flag on/off - * array $array of levels to turn on/off debug - * @return bool Return false if type or flag is invalid - * @deprecated Use setLogLevel - */ - public function debugFor(string $type, string $flag): bool - { - /** @phan-suppress-next-line PhanTypeMismatchArgumentReal, PhanParamTooFew @phpstan-ignore-next-line */ - return $this->setLogLevel(...[func_get_args()]); - } - - /** - * set log level settings for All types - * if invalid type, skip - * - * @param string $type Type to get: debug, echo, print - * @param bool $set True or False - * @return bool Return false if type invalid - */ - public function setLogLevelAll(string $type, bool $set): bool - { - // skip set if not valid - if (!in_array($type, ['debug', 'echo', 'print'])) { - return false; - } - $this->{$type . '_output_all'} = $set; - return true; - } - - /** - * get the current log level setting for All level blocks - * - * @param string $type Type to get: debug, echo, print - * @return bool False on failure, or the boolean flag from the all var - */ - public function getLogLevelAll(string $type): bool - { - // type check for debug/echo/print - if (!in_array($type, ['debug', 'echo', 'print'])) { - return false; - } - return $this->{$type . '_output_all'}; - } - - /** - * passes list of level names, to turn on debug - * eg $foo->debugFor('print', 'on', ['LOG', 'DEBUG', 'INFO']); - * - * @param string $type debug, echo, print - * @param string $flag on/off - * @param array $debug_on Array of levels to turn on/off debug - * To turn off a level set 'Level' => false, - * If not set, switches to on - * @return bool Return false if type or flag invalid - * also false if debug array is empty - */ - public function setLogLevel(string $type, string $flag, array $debug_on): bool - { - // abort if not valid type - if (!in_array($type, ['debug', 'echo', 'print'])) { - return false; - } - // invalid flag type - if (!in_array($flag, ['on', 'off'])) { - return false; - } - if (count($debug_on) >= 1) { - foreach ($debug_on as $level => $set) { - $switch = $type . '_output' . ($flag == 'off' ? '_not' : ''); - if (!is_bool($set)) { - $level = $set; - $set = true; - } - $this->{$switch}[$level] = $set; - } - } else { - return false; - } - return true; - } - - /** - * return the log level for the array type normal and not (disable) - * - * @param string $type debug, echo, print - * @param string $flag on/off - * @param string|null $level if not null then check if this array entry is set - * else return false - * @return array|bool if $level is null, return array, else boolean true/false - */ - public function getLogLevel(string $type, string $flag, ?string $level = null): array|bool - { - // abort if not valid type - if (!in_array($type, ['debug', 'echo', 'print'])) { - return false; - } - // invalid flag type - if (!in_array($flag, ['on', 'off'])) { - return false; - } - $switch = $type . '_output' . ($flag == 'off' ? '_not' : ''); - // log level direct check must be not null or not empty string - if (!empty($level)) { - return $this->{$switch}[$level] ?? false; - } - // array - return $this->{$switch}; - } - - /** - * set flags for per log level type - * - level: set per sub group level - * - class: split by class - * - page: split per page called - * - run: for each run - * - * @param string $type Type to get: level, class, page, run - * @param bool $set True or False - * @return bool Return false if type invalid - */ - public function setLogPer(string $type, bool $set): bool - { - if (!in_array($type, ['level', 'class', 'page', 'run'])) { - return false; - } - $this->{'log_per_' . $type} = $set; - // if per run set unique id - if ($type == 'run' && $set == true) { - $this->setLogUniqueId(); - } - return true; - } - - /** - * return current set log per flag in bool - * - * @param string $type Type to get: level, class, page, run - * @return bool True of false for turned on or off - */ - public function getLogPer(string $type): bool - { - if (!in_array($type, ['level', 'class', 'page', 'run'])) { - return false; - } - return $this->{'log_per_' . $type}; - } - - /** - * Sets a unique id based on current date (y/m/d, h:i:s) and a unique id (8 chars) - * if override is set to true it will be newly set, else if already set nothing changes - * - * @param bool $override True to force new set - * @return void - */ - public function setLogUniqueId(bool $override = false): void - { - if (!$this->log_file_unique_id || $override == true) { - $this->log_file_unique_id = - date('Y-m-d_His') . '_U_' - . substr(hash('sha1', uniqid((string)mt_rand(), true)), 0, 8); - } - } - - /** - * Return current set log file unique id, - * empty string for not set - * - * @return string - */ - public function getLogUniqueId(): string - { - return $this->log_file_unique_id; - } - - /** - * Set or get the log file date extension flag - * if null or empty parameter gets current flag - * - * @param boolean|null $set Set the date suffix for log files - * If set to null return current set - * @return boolean Current set flag - */ - public function setGetLogPrintFileDate(?bool $set = null): bool - { - if ($set !== null) { - $this->log_print_file_date = $set; - } - return $this->log_print_file_date; - } - - /** - * Return current set log file name - * - * @return string Filename set set after the last time debug was called - */ - public function getLogFileName(): string - { - return $this->log_file_name; - } - - /** - * A replacement for the \CoreLibs\Debug\Support::printAr - * But this does not wrap it in

-	 * It uses some special code sets so we can convert that to pre flags
-	 * for echo output {##HTMLPRE##} ... {##/HTMLPRE##}
-	 * Do not use this without using it in a string in debug function
-	 *
-	 * @param  array $a Array to format
-	 * @return string          print_r formated
-	 */
-	public function prAr(array $a): string
-	{
-		return '##HTMLPRE##' . print_r($a, true) . '##/HTMLPRE##';
-	}
-
-	/**
-	 * Convert bool value to string value
-	 *
-	 * @param  bool   $bool  Bool value to be transformed
-	 * @param  string $true  Override default string 'true'
-	 * @param  string $false Override default string 'false'
-	 * @return string        $true or $false string for true/false bool
-	 */
-	public function prBl(
-		bool $bool,
-		string $true = 'true',
-		string $false = 'false'
-	): string {
-		return $bool ? $true : $false;
-	}
-
-	/**
-	 * write debug data to error_msg array
-	 *
-	 * @param  string $level  id for error message, groups messages together
-	 * @param  string $string the actual error message
-	 * @param  bool   $strip  default on false, if set to true,
-	 *                        all html tags will be stripped and 
changed to \n - * this is only used for debug output - * @param string $prefix Attach some block before $string. - * Will not be stripped even - * when strip is true - * if strip is false, recommended to add that to $string - * @return bool True if logged, false if not logged - */ - public function debug( - string $level, - string $string, - bool $strip = false, - string $prefix = '' - ): bool { - $status = false; - // must be debug on and either echo or print on - if ( - !$this->doDebugTrigger('debug', $level) || - ( - // if debug is on, either print or echo must be set to on - !$this->doDebugTrigger('print', $level) && - !$this->doDebugTrigger('echo', $level) - ) - ) { - return $status; - } - // get the last class entry and wrie that - $class = Support::getCallerClass(); - // get timestamp - $timestamp = Support::printTime(); - // same string put for print (no html data inside) - // write to file if set - $status = $this->writeErrorMsg( - $level, - '[' . $timestamp . '] ' - . '[' . $this->host_name . '] ' - . '[' . System::getPageName(System::FULL_PATH) . '] ' - . '[' . $this->running_uid . '] ' - . '{' . $class . '} ' - . '<' . $level . '> - ' - // strip the htmlpre special tags if exist - . str_replace( - ['##HTMLPRE##', '##/HTMLPRE##'], - '', - // if stripping all html, etc is requested, only for write error msg - ($strip ? - // find any
and replace them with \n - // strip rest of html elements (base only) - preg_replace( - "/(<\/?)(\w+)([^>]*>)/", - '', - str_replace('
', "\n", $prefix . $string) - ) : - $prefix . $string - ) ?: '' - ) - . "\n" - ); - // write to error level msg array if there is an echo request - if ($this->doDebugTrigger('echo', $level)) { - // init if not set - if (!isset($this->error_msg[$level])) { - $this->error_msg[$level] = []; - } - // HTML string - $this->error_msg[$level][] = '
' - . '[' . $timestamp . '] ' - . '[' . $level . '] ' - . '[' . $this->host_name . '] ' - . '[' . $this->page_name . '] ' - . '[' . $this->running_uid . '] ' - . '{' . $class . '} - ' - // as is prefix, allow HTML - . $prefix - // we replace special HTMLPRE with
 entries
-				. str_replace(
-					['##HTMLPRE##', '##/HTMLPRE##'],
-					['
', '
'], - Html::htmlent($string) - ) - . "
"; - $status = true; - } - return $status; - } - - /** - * for ECHO ON only - * returns error data as string so it can be echoed out - * - * @param string $header_prefix prefix string for header - * @return string error msg for all levels - */ - public function printErrorMsg(string $header_prefix = ''): string - { - $string_output = ''; - // if not debug && echo on, do not return anything - if ( - !$this->getLogLevelAll('debug') || - !$this->getLogLevelAll('echo') - ) { - return $string_output; - } - if ($this->error_msg_prefix) { - $header_prefix = $this->error_msg_prefix; - } - $script_end = microtime(true) - $this->script_starttime; - foreach ($this->error_msg as $level => $temp_debug_output) { - if ($this->doDebugTrigger('debug', $level)) { - if ($this->doDebugTrigger('echo', $level)) { - $string_output .= '
' - . '[' . $level . '] ' - . ($header_prefix ? "**** " . Html::htmlent($header_prefix) . " ****
\n" : '') - . '
' - . join('', $temp_debug_output); - } // echo it out - } // do printout - } // for each level - // create the output wrapper around - // so we have a nice formated output per class - if ($string_output) { - $string_prefix = '
' - . '
{' - . Support::getCallerClass() . '}
'; - $string_output = $string_prefix . $string_output - . '
Script Run Time: ' - . $script_end . '
' - . '
'; - } - // } - return $string_output; - } - - /** - * for ECHO ON only - * unsests the error message array - * can be used if writing is primary to file - * if no level given resets all - * - * @param string $level optional level - * @return void has no return - */ - public function resetErrorMsg(string $level = ''): void - { - if (!$level) { - $this->error_msg = []; - } elseif (isset($this->error_msg[$level])) { - unset($this->error_msg[$level]); - } - } - - /** - * for ECHO ON only - * Get current error message array - * - * @return array error messages collected - */ - public function getErrorMsg(): array - { - return $this->error_msg; - } - - /** - * for ECHO ON only - * merges the given error array with the one from this class - * only merges visible ones - * - * @param array $error_msg error array - * @return void has no return - */ - public function mergeErrors(array $error_msg = []): void - { - array_push($this->error_msg, ...$error_msg); + parent::__construct($options); } } diff --git a/www/lib/CoreLibs/Debug/LoggingLegacy.php b/www/lib/CoreLibs/Debug/LoggingLegacy.php new file mode 100644 index 00000000..6d3a6029 --- /dev/null +++ b/www/lib/CoreLibs/Debug/LoggingLegacy.php @@ -0,0 +1,911 @@ + */ + private $options = []; + // page and host name + /** @var string */ + private $page_name; + /** @var string */ + private $host_name; + /** @var int */ + private $host_port; + // internal error reporting vars + /** @var array */ + private $error_msg = []; // the "connection" to the outside errors + // debug output prefix + /** @var string */ + private $error_msg_prefix = ''; // prefix to the error string (the class name) + + // debug flags/settings + /** @var string */ + private $running_uid = ''; // unique ID set on class init and used in logging as prefix + // log file name + /** @var string */ + private $log_folder = ''; + /** @var string */ + private $log_file_name_ext = 'log'; // use this for date rotate + /** @var string */ + private $log_file_name = ''; + /** @var int */ + private $log_max_filesize = 0; // set in kilobytes + /** @var string */ + private $log_print_file = 'error_msg{LOGID}{LEVEL}{CLASS}{PAGENAME}{DATE_RUNID}'; + /** @var string */ + private $log_file_unique_id; // a unique ID set only once for call derived from this class + /** @var string */ + private $log_file_date = ''; // Y-m-d file in file name + /** @var bool */ + private $log_print_file_date = true; // if set add Y-m-d and do automatic daily rotation + /** @var string */ + private $log_file_id = ''; // a alphanumeric name that has to be set as global definition + /** @var bool */ + private $log_per_level = false; // set, it will split per level (first parameter in debug call) + /** @var bool */ + private $log_per_class = false; // set, will split log per class + /** @var bool */ + private $log_per_page = false; // set, will split log per called file + /** @var bool */ + private $log_per_run = false; // create a new log file per run (time stamp + unique ID) + // script running time + /** @var float */ + private $script_starttime; + + /** @var string[] current log levels */ + private $log_levels = ['debug', 'echo', 'print']; + /** @var string[] log group per what for writing to file */ + private $log_grouping = ['level', 'class', 'page', 'run']; + + // debug flags [they must exist or we get a warning] + /** @var array */ + private $debug_output = []; // if this is true, show debug on desconstructor + /** @var array */ + private $debug_output_not = []; + /** @var bool */ + private $debug_output_all = false; + /** @var array */ + private $echo_output = []; // errors: echo out, default is 1 + /** @var array */ + private $echo_output_not = []; + /** @var bool */ + private $echo_output_all = false; + /** @var array */ + private $print_output = []; // errors: print to file, default is 0 + /** @var array */ + private $print_output_not = []; + /** @var bool */ + private $print_output_all = false; + + /** + * Init logger + * + * global vars that can be used + * - BASE + * - LOG + * - LOG_FILE_ID + * options array layout + * - log_folder: + * - file_id: + * - unique_id: + * - print_file_date: + * - log_per_level: + * - log_per_class: + * - log_per_page: + * - log_per_run: + * - debug_all: + * - echo_all: + * - print_all: + * - debug (array): + * - echo (array): + * - print (array): + * - debug_not (array): + * - echo_not (array): + * - print_not (array): + * + * @param array $options Array with settings options + */ + public function __construct(array $options = []) + { + // copy the options over + $this->options = $options; + // set log folder from options + $this->log_folder = $this->options['log_folder'] ?? ''; + // legacy flow, check must set constants + if (empty($this->log_folder) && defined('BASE') && defined('LOG')) { + /** @deprecated Do not use this anymore, define path on class load */ + trigger_error( + 'options: log_folder must be set. Setting via BASE and LOG constants is deprecated', + E_USER_DEPRECATED + ); + // make sure this is writeable, else skip + $this->log_folder = BASE . LOG; + } + // fallback + notice + if (empty($this->log_folder)) { + /* trigger_error( + 'options or constant not set or folder not writable. fallback to: ' . getcwd(), + E_USER_NOTICE + ); */ + $this->log_folder = getcwd() . DIRECTORY_SEPARATOR; + } + // if folder is not writeable, abort + if (!is_writeable($this->log_folder)) { + trigger_error( + 'Folder: ' . $this->log_folder . ' is not writeable for logging', + E_USER_ERROR + ); + } + // check if log_folder has a trailing / + if (substr($this->log_folder, -1, 1) != DIRECTORY_SEPARATOR) { + $this->log_folder .= DIRECTORY_SEPARATOR; + } + // running time start for script + $this->script_starttime = microtime(true); + // set per run UID for logging + $this->running_uid = Uids::uniqIdShort(); + // set the page name + $this->page_name = System::getPageName(); + // set host name + list($this->host_name , $this->host_port) = System::getHostName(); + // add port to host name if not port 80 + if ($this->host_port != 80) { + $this->host_name .= ':' . $this->host_port; + } + + // can be overridden with basicSetLogFileId later + if (!empty($this->options['file_id'])) { + $this->setLogId($this->options['file_id']); + } elseif (!empty($GLOBALS['LOG_FILE_ID'])) { + /** @deprecated Do not use this anymore, define file_id on class load */ + trigger_error( + 'options: file_id must be set. Setting via LOG_FILE_ID global variable is deprecated', + E_USER_DEPRECATED + ); + // legacy flow, should be removed and only set via options + $this->setLogId($GLOBALS['LOG_FILE_ID']); + // TODO trigger deprecation error + // trigger_error( + // 'Debug\Logging: Do not use globals LOG_FILE_ID to set log id for Logging', + // E_USER_DEPRECATED + // ); + } elseif (defined('LOG_FILE_ID')) { + /** @deprecated Do not use this anymore, define file_id on class load */ + trigger_error( + 'options: file_id must be set. Setting via LOG_FILE_ID constant is deprecated', + E_USER_DEPRECATED + ); + // legacy flow, should be removed and only set via options + $this->setLogId((string)LOG_FILE_ID); + // trigger deprecation error + // trigger_error( + // 'Debug\Logging: Do not use constant LOG_FILE_ID to set log id for Logging', + // E_USER_DEPRECATED + // ); + } + + // init the log levels + $this->initLogLevels(); + } + + // *** PRIVATE *** + + /** + * init the basic log levels based on global set variables + * + * @return void + */ + private function initLogLevels(): void + { + // if given via parameters, only for all + // globals overrule given settings, for one (array), eg $ECHO['db'] = 1; + foreach ($this->log_levels as $type) { + // include or exclude (off) from output + foreach (['on', 'off'] as $flag) { + $in_type = $type; + if ($flag == 'off') { + $in_type .= '_not'; + } + $up_type = strtoupper($in_type); + if ( + isset($this->options[$in_type]) && + is_array($this->options[$in_type]) + ) { + $this->setLogLevel($type, $flag, $this->options[$in_type]); + } elseif ( + isset($GLOBALS[$up_type]) && + is_array($GLOBALS[$up_type]) + ) { + // TODO trigger deprecation error + $this->setLogLevel($type, $flag, $GLOBALS[$up_type]); + } + } + } + + // TODO remove all $GLOBALS call and only use options + // all overrule + $this->setLogLevelAll( + 'debug', + $this->options['debug_all'] ?? + // for user login, should be handled outside like globals + $_SESSION['DEBUG_ALL'] ?? // DEPRECATED + $GLOBALS['DEBUG_ALL'] ?? // DEPRECATED + false + ); + $this->setLogLevelAll( + 'print', + $this->options['print_all'] ?? + // for user login, should be handled outside like globals + $_SESSION['DEBUG_ALL'] ?? // DEPRECATED + $GLOBALS['PRINT_ALL'] ?? // DEPRECATED + false + ); + $this->setLogLevelAll( + 'echo', + $this->options['echo_all'] ?? + $GLOBALS['ECHO_ALL'] ?? // DEPRECATED + false + ); + + // GLOBAL rules for log writing + // add file date is default on + $this->setGetLogPrintFileDate( + $this->options['print_file_date'] ?? + $GLOBALS['LOG_PRINT_FILE_DATE'] ?? // DEPRECATED + true + ); + // all other logging file name flags are off + $this->setLogPer( + 'level', + $this->options['per_level'] ?? + $GLOBALS['LOG_PER_LEVEL'] ?? // DEPRECATED + false + ); + $this->setLogPer( + 'class', + $this->options['per_class'] ?? + $GLOBALS['LOG_PER_CLASS'] ?? // DEPRECATED + false + ); + $this->setLogPer( + 'page', + $this->options['per_page'] ?? + $GLOBALS['LOG_PER_PAGE'] ?? // DEPRECATED + false + ); + $this->setLogPer( + 'run', + $this->options['per_run'] ?? + $GLOBALS['LOG_PER_RUN'] ?? // DEPRECATED + false + ); + // set log per date + if ($this->setGetLogPrintFileDate()) { + $this->log_file_date = date('Y-m-d'); + } + // set per run ID + if ($this->log_per_run) { + $this->setLogUniqueId(); + } + } + + /** + * checks if we have a need to work on certain debug output + * Needs debug/echo/print ad target for which of the debug flag groups we check + * also needs level string to check in the per level output flag check. + * In case we have invalid target it will return false + * + * @param string $target target group to check debug/echo/print + * @param string $level level to check in detailed level flag + * @return bool true on access allowed or false on no access + */ + private function doDebugTrigger(string $target, string $level): bool + { + $access = false; + // check if we do debug, echo or print + if ( + ( + $this->getLogLevel($target, 'on', $level) || + $this->getLogLevelAll($target) + ) && + !$this->getLogLevel($target, 'off', $level) + ) { + $access = true; + } + return $access; + } + + /** + * writes error msg data to file for current level + * + * @param string $level the level to write + * @param string $error_string error string to write + * @return bool True if message written, False if not + */ + private function writeErrorMsg(string $level, string $error_string): bool + { + // only write if write is requested + if ( + !($this->doDebugTrigger('debug', $level) && + $this->doDebugTrigger('print', $level)) + ) { + return false; + } + + // init base file path + $fn = $this->log_folder . $this->log_print_file . '.' . $this->log_file_name_ext; + // log ID prefix settings, if not valid, replace with empty + if (!empty($this->log_file_id)) { + $rpl_string = '_' . $this->log_file_id; + } else { + $rpl_string = ''; + } + $fn = str_replace('{LOGID}', $rpl_string, $fn); // log id (like a log file prefix) + + // if run id, we auto add ymd, so we ignore the log file date + if ($this->log_per_run) { + $rpl_string = '_' . $this->log_file_unique_id; // add 8 char unique string + } elseif ($this->setGetLogPrintFileDate()) { + $rpl_string = '_' . $this->log_file_date; // add date to file + } else { + $rpl_string = ''; + } + $fn = str_replace('{DATE_RUNID}', $rpl_string, $fn); // create output filename + + // write per level + $rpl_string = !$this->log_per_level ? '' : + // normalize level, replace all non alphanumeric characters with - + '_' . ( + // if return is only - then set error string + preg_match( + "/^-+$/", + $level_string = preg_replace("/[^A-Za-z0-9-_]/", '-', $level) ?? '' + ) ? + 'INVALID-LEVEL-STRING' : + $level_string + ); + $fn = str_replace('{LEVEL}', $rpl_string, $fn); // create output filename + // set per class, but don't use get_class as we will only get self + $rpl_string = !$this->log_per_class ? '' : '_' + // set sub class settings + . str_replace('\\', '-', Support::getCallerClass()); + $fn = str_replace('{CLASS}', $rpl_string, $fn); // create output filename + + // if request to write to one file + $rpl_string = !$this->log_per_page ? + '' : + '_' . System::getPageName(System::NO_EXTENSION); + $fn = str_replace('{PAGENAME}', $rpl_string, $fn); // create output filename + + // write to file + // first check if max file size is is set and file is bigger + if ( + $this->log_max_filesize > 0 && + ((filesize($fn) / 1024) > $this->log_max_filesize) + ) { + // for easy purpose, rename file only to attach timestamp, nur sequence numbering + rename($fn, $fn . '.' . date("YmdHis")); + } + $this->log_file_name = $fn; + $fp = fopen($this->log_file_name, 'a'); + if ($fp !== false) { + fwrite($fp, $error_string); + fclose($fp); + return true; + } else { + echo ""; + return false; + } + } + + // *** PUBLIC *** + + /** + * Temporary method to read all class variables for testing purpose + * + * @param string $name what variable to return + * @return mixed can be anything, bool, string, int, array + */ + public function getSetting(string $name): mixed + { + // for debug purpose only + return $this->{$name}; + } + + /** + * sets the internal log file prefix id + * string must be a alphanumeric string + * if non valid string is given it returns the previous set one only + * + * @param string $string log file id string value + * @return string returns the set log file id string + * @deprecated Use $log->setLogId() + */ + public function basicSetLogId(string $string): string + { + return $this->setLogId($string); + } + + /** + * sets the internal log file prefix id + * string must be a alphanumeric string + * if non valid string is given it returns the previous set one only + * + * @param string $string log file id string value + * @return string returns the set log file id string + */ + public function setLogId(string $string): string + { + if (preg_match("/^[\w\-]+$/", $string)) { + $this->log_file_id = $string; + } + return $this->log_file_id; + } + + /** + * return current set log file id + * @return string + */ + public function getLogId(): string + { + return $this->log_file_id; + } + + /** + * old name for setLogLevel + * + * @param string $type debug, echo, print + * @param string $flag on/off + * array $array of levels to turn on/off debug + * @return bool Return false if type or flag is invalid + * @deprecated Use setLogLevel + */ + public function debugFor(string $type, string $flag): bool + { + /** @phan-suppress-next-line PhanTypeMismatchArgumentReal, PhanParamTooFew @phpstan-ignore-next-line */ + return $this->setLogLevel(...[func_get_args()]); + } + + /** + * set log level settings for All types + * if invalid type, skip + * + * @param string $type Type to get: debug, echo, print + * @param bool $set True or False + * @return bool Return false if type invalid + */ + public function setLogLevelAll(string $type, bool $set): bool + { + // skip set if not valid + if (!in_array($type, $this->log_levels)) { + return false; + } + $this->{$type . '_output_all'} = $set; + return true; + } + + /** + * get the current log level setting for All level blocks + * + * @param string $type Type to get: debug, echo, print + * @return bool False on failure, or the boolean flag from the all var + */ + public function getLogLevelAll(string $type): bool + { + // type check for debug/echo/print + if (!in_array($type, $this->log_levels)) { + return false; + } + return $this->{$type . '_output_all'}; + } + + /** + * passes list of level names, to turn on debug + * eg $foo->debugFor('print', 'on', ['LOG', 'DEBUG', 'INFO']); + * + * @param string $type debug, echo, print + * @param string $flag on/off + * @param array $debug_on Array of levels to turn on/off debug + * To turn off a level set 'Level' => false, + * If not set, switches to on + * @return bool Return false if type or flag invalid + * also false if debug array is empty + */ + public function setLogLevel(string $type, string $flag, array $debug_on): bool + { + // abort if not valid type + if (!in_array($type, $this->log_levels)) { + return false; + } + // invalid flag type + if (!in_array($flag, ['on', 'off'])) { + return false; + } + if (count($debug_on) >= 1) { + foreach ($debug_on as $level => $set) { + $switch = $type . '_output' . ($flag == 'off' ? '_not' : ''); + if (!is_bool($set)) { + $level = $set; + $set = true; + } + $this->{$switch}[$level] = $set; + } + } else { + return false; + } + return true; + } + + /** + * return the log level for the array type normal and not (disable) + * + * @param string $type debug, echo, print + * @param string $flag on/off + * @param string|null $level if not null then check if this array entry is set + * else return false + * @return array|bool if $level is null, return array, else boolean true/false + */ + public function getLogLevel(string $type, string $flag, ?string $level = null): array|bool + { + // abort if not valid type + if (!in_array($type, $this->log_levels)) { + return false; + } + // invalid flag type + if (!in_array($flag, ['on', 'off'])) { + return false; + } + $switch = $type . '_output' . ($flag == 'off' ? '_not' : ''); + // log level direct check must be not null or not empty string + if (!empty($level)) { + return $this->{$switch}[$level] ?? false; + } + // array + return $this->{$switch}; + } + + /** + * set flags for per log level type + * - level: set per sub group level + * - class: split by class + * - page: split per page called + * - run: for each run + * + * @param string $type Type to get: level, class, page, run + * @param bool $set True or False + * @return bool Return false if type invalid + */ + public function setLogPer(string $type, bool $set): bool + { + if (!in_array($type, $this->log_grouping)) { + return false; + } + $this->{'log_per_' . $type} = $set; + // if per run set unique id + if ($type == 'run' && $set == true) { + $this->setLogUniqueId(); + } + return true; + } + + /** + * return current set log per flag in bool + * + * @param string $type Type to get: level, class, page, run + * @return bool True of false for turned on or off + */ + public function getLogPer(string $type): bool + { + if (!in_array($type, $this->log_grouping)) { + return false; + } + return $this->{'log_per_' . $type}; + } + + /** + * Sets a unique id based on current date (y/m/d, h:i:s) and a unique id (8 chars) + * if override is set to true it will be newly set, else if already set nothing changes + * + * @param bool $override True to force new set + * @return void + */ + public function setLogUniqueId(bool $override = false): void + { + if (!$this->log_file_unique_id || $override == true) { + $this->log_file_unique_id = + date('Y-m-d_His') . '_U_' + . substr(hash('sha1', uniqid((string)mt_rand(), true)), 0, 8); + } + } + + /** + * Return current set log file unique id, + * empty string for not set + * + * @return string + */ + public function getLogUniqueId(): string + { + return $this->log_file_unique_id; + } + + /** + * Set or get the log file date extension flag + * if null or empty parameter gets current flag + * + * @param boolean|null $set Set the date suffix for log files + * If set to null return current set + * @return boolean Current set flag + */ + public function setGetLogPrintFileDate(?bool $set = null): bool + { + if ($set !== null) { + $this->log_print_file_date = $set; + } + return $this->log_print_file_date; + } + + /** + * Return current set log file name + * + * @return string Filename set set after the last time debug was called + */ + public function getLogFileName(): string + { + return $this->log_file_name; + } + + /** + * A replacement for the \CoreLibs\Debug\Support::printAr + * But this does not wrap it in

+	 * It uses some special code sets so we can convert that to pre flags
+	 * for echo output {##HTMLPRE##} ... {##/HTMLPRE##}
+	 * Do not use this without using it in a string in debug function
+	 *
+	 * @param  array $a Array to format
+	 * @return string          print_r formated
+	 */
+	public function prAr(array $a): string
+	{
+		return '##HTMLPRE##' . print_r($a, true) . '##/HTMLPRE##';
+	}
+
+	/**
+	 * Convert bool value to string value
+	 *
+	 * @param  bool   $bool  Bool value to be transformed
+	 * @param  string $true  Override default string 'true'
+	 * @param  string $false Override default string 'false'
+	 * @return string        $true or $false string for true/false bool
+	 */
+	public function prBl(
+		bool $bool,
+		string $true = 'true',
+		string $false = 'false'
+	): string {
+		return $bool ? $true : $false;
+	}
+
+	/**
+	 * write debug data to error_msg array
+	 *
+	 * @param  string $level  id for error message, groups messages together
+	 * @param  string $string the actual error message
+	 * @param  bool   $strip  default on false, if set to true,
+	 *                        all html tags will be stripped and 
changed to \n + * this is only used for debug output + * @param string $prefix Attach some block before $string. + * Will not be stripped even + * when strip is true + * if strip is false, recommended to add that to $string + * @return bool True if logged, false if not logged + */ + public function debug( + string $level, + string $string, + bool $strip = false, + string $prefix = '' + ): bool { + $status = false; + // must be debug on and either echo or print on + if ( + !$this->doDebugTrigger('debug', $level) || + ( + // if debug is on, either print or echo must be set to on + !$this->doDebugTrigger('print', $level) && + !$this->doDebugTrigger('echo', $level) + ) + ) { + return $status; + } + // get the last class entry and wrie that + $class = Support::getCallerClass(); + // get timestamp + $timestamp = Support::printTime(); + // same string put for print (no html data inside) + // write to file if set + $status = $this->writeErrorMsg( + $level, + '[' . $timestamp . '] ' + . '[' . $this->host_name . '] ' + . '[' . System::getPageName(System::FULL_PATH) . '] ' + . '[' . $this->running_uid . '] ' + . '{' . $class . '} ' + . '<' . $level . '> - ' + // strip the htmlpre special tags if exist + . str_replace( + ['##HTMLPRE##', '##/HTMLPRE##'], + '', + // if stripping all html, etc is requested, only for write error msg + ($strip ? + // find any
and replace them with \n + // strip rest of html elements (base only) + preg_replace( + "/(<\/?)(\w+)([^>]*>)/", + '', + str_replace('
', "\n", $prefix . $string) + ) : + $prefix . $string + ) ?: '' + ) + . "\n" + ); + // write to error level msg array if there is an echo request + if ($this->doDebugTrigger('echo', $level)) { + // init if not set + if (!isset($this->error_msg[$level])) { + $this->error_msg[$level] = []; + } + // HTML string + $this->error_msg[$level][] = '
' + . '[' . $timestamp . '] ' + . '[' . $level . '] ' + . '[' . $this->host_name . '] ' + . '[' . $this->page_name . '] ' + . '[' . $this->running_uid . '] ' + . '{' . $class . '} - ' + // as is prefix, allow HTML + . $prefix + // we replace special HTMLPRE with
 entries
+				. str_replace(
+					['##HTMLPRE##', '##/HTMLPRE##'],
+					['
', '
'], + Html::htmlent($string) + ) + . "
"; + $status = true; + } + return $status; + } + + /** + * for ECHO ON only + * returns error data as string so it can be echoed out + * + * @param string $header_prefix prefix string for header + * @return string error msg for all levels + */ + public function printErrorMsg(string $header_prefix = ''): string + { + $string_output = ''; + // if not debug && echo on, do not return anything + if ( + !$this->getLogLevelAll('debug') || + !$this->getLogLevelAll('echo') + ) { + return $string_output; + } + if ($this->error_msg_prefix) { + $header_prefix = $this->error_msg_prefix; + } + $script_end = microtime(true) - $this->script_starttime; + foreach ($this->error_msg as $level => $temp_debug_output) { + if ($this->doDebugTrigger('debug', $level)) { + if ($this->doDebugTrigger('echo', $level)) { + $string_output .= '
' + . '[' . $level . '] ' + . ($header_prefix ? "**** " . Html::htmlent($header_prefix) . " ****
\n" : '') + . '
' + . join('', $temp_debug_output); + } // echo it out + } // do printout + } // for each level + // create the output wrapper around + // so we have a nice formated output per class + if ($string_output) { + $string_prefix = '
' + . '
{' + . Support::getCallerClass() . '}
'; + $string_output = $string_prefix . $string_output + . '
Script Run Time: ' + . $script_end . '
' + . '
'; + } + // } + return $string_output; + } + + /** + * for ECHO ON only + * unsests the error message array + * can be used if writing is primary to file + * if no level given resets all + * + * @param string $level optional level + * @return void has no return + */ + public function resetErrorMsg(string $level = ''): void + { + if (!$level) { + $this->error_msg = []; + } elseif (isset($this->error_msg[$level])) { + unset($this->error_msg[$level]); + } + } + + /** + * for ECHO ON only + * Get current error message array + * + * @return array error messages collected + */ + public function getErrorMsg(): array + { + return $this->error_msg; + } + + /** + * for ECHO ON only + * merges the given error array with the one from this class + * only merges visible ones + * + * @param array $error_msg error array + * @return void has no return + */ + public function mergeErrors(array $error_msg = []): void + { + array_push($this->error_msg, ...$error_msg); + } +} + +// __END__ diff --git a/www/lib/CoreLibs/Debug/Support.php b/www/lib/CoreLibs/Debug/Support.php index c4a322b2..7f43688b 100644 --- a/www/lib/CoreLibs/Debug/Support.php +++ b/www/lib/CoreLibs/Debug/Support.php @@ -37,23 +37,21 @@ class Support * prints a html formatted (pre) array * * @param array $array any array - * @param bool $no_html set to true to use ##HTMLPRE## + * @param bool $no_html default add
 	 * @return string                formatted array for output with 
 tag added
 	 */
 	public static function printAr(array $array, bool $no_html = false): string
 	{
-		if ($no_html === false) {
-			return "
" . print_r($array, true) . "
"; - } else { - return '##HTMLPRE##' . print_r($array, true) . '##/HTMLPRE##'; - } + return $no_html ? + print_r($array, true) : + '
' . print_r($array, true) . '
'; } /** * alternate name for printAr function * * @param array $array any array - * @param bool $no_html set to true to use ##HTMLPRE## + * @param bool $no_html default add
 	 * @return string                formatted array for output with 
 tag added
 	 */
 	public static function printArray(array $array, bool $no_html = false): string
@@ -61,26 +59,61 @@ class Support
 		return self::printAr($array, $no_html);
 	}
 
+	/**
+	 * A replacement for the \CoreLibs\Debug\Support::printAr
+	 * But this does not wrap it in 

+	 * Do not use this without using it in a string in debug function
+	 * Note: for full data debug dumps use Support::dumpVar()
+	 *
+	 * @param  array $a Array to format
+	 * @return string          print_r formated
+	 */
+	public static function prAr(array $a): string
+	{
+		return self::printAr($a, true);
+	}
+
 	/**
 	 * convert bool value to string
 	 * if $name is set prefix with nae
 	 * default true: true, false: false
 	 *
-	 * @param  bool   $bool  Variable to convert
-	 * @param  string $name  [default: ''] Prefix name
-	 * @param  string $true  [default: true] True string
-	 * @param  string $false [default: false] False string
-	 * @return string        String with converted bool text for debug
+	 * @param  bool   $bool    Variable to convert
+	 * @param  string $name    [default: ''] Prefix name
+	 * @param  string $true    [default: 'true'] True string
+	 * @param  string $false   [default: 'false'] False string
+	 * @param  bool   $no_html [default: false] if true do not print html
+	 * @return string          String with converted bool text for debug
 	 */
 	public static function printBool(
 		bool $bool,
 		string $name = '',
 		string $true = 'true',
+		string $false = 'false',
+		bool $no_html = false,
+	): string {
+		return
+			(!empty($name) ?
+				($no_html ?
+					$name : '' . $name . '') . ': '
+				: '')
+			. ($bool ? $true : $false);
+	}
+
+	/**
+	 * Convert bool value to string value. Short name alias for printBool
+	 *
+	 * @param  bool   $bool  Bool value to be transformed
+	 * @param  string $true  [default: 'true'] Override default string 'true'
+	 * @param  string $false [default: 'false'] Override default string 'false'
+	 * @return string        $true or $false string for true/false bool
+	 */
+	public static function prBl(
+		bool $bool,
+		string $true = 'true',
 		string $false = 'false'
 	): string {
-		$string = (!empty($name) ? '' . $name . ': ' : '')
-			. ($bool ? $true : $false);
-		return $string;
+		return self::printBool($bool, '', $true, $false, true);
 	}
 
 	/**
@@ -89,9 +122,10 @@ class Support
 	 * if object return get_class
 	 * for array use printAr function, can be controlled with no_html for
 	 * Debug\Logging compatible output
+	 * Recommended to use Support::dumpVar()
 	 *
 	 * @param  mixed  $mixed
-	 * @param  bool   $no_html set to true to use ##HTMLPRE##or html escape
+	 * @param  bool   $no_html set to true to strip 
 tags
 	 * @return string
 	 */
 	public static function printToString(mixed $mixed, bool $no_html = false): string
@@ -119,12 +153,80 @@ class Support
 		}
 	}
 
+	/**
+	 * Dumps var data and returns it as string
+	 * var_dump based
+	 * Recommended debug output
+	 *
+	 * @param  mixed  $data    Anything
+	 * @param  bool   $no_html If true strip all html tags (for text print)
+	 * @return string          A text string
+	 */
+	public static function dumpVar(mixed $data, bool $no_html = false): string
+	{
+		ob_start();
+		var_dump($data);
+		$debug_dump = ob_get_clean() ?: '[FAILED TO GET var_dump() data]';
+		// we need to strip the string in :
+		// and replace it with the caller methods and location
+		$caller_file_number = self::getCallerFileLine();
+		$debug_dump = preg_replace(
+			'|(/.*:\d+:)|',
+			'' . $caller_file_number . ':',
+			$debug_dump
+		) ?? $debug_dump; // in case of failure keep original
+		// if strip is ture, remove all HTML tags and convert any html entities back
+		return $no_html ?
+			str_replace(
+				// things to replace in the string if set
+				['>', '<', '
', '
'],
+				['>', '<', "\r", "\n"],
+				strip_tags($debug_dump)
+			) :
+			$debug_dump;
+	}
+
+	/**
+	 * exports (dumps) var, in more printable design, but without detail info
+	 *
+	 * @param  mixed  $data    Anything
+	 * @param  bool   $no_html If true true do not add 
 tags
+	 * @return string          A text string
+	 */
+	public static function exportVar(mixed $data, bool $no_html = false): string
+	{
+		return $no_html ?
+			var_export($data, true) :
+			'
' . var_export($data, true) . '
'; + } + + /** + * Return file name and line number where this was called + * One level up + * + * @param int $level trace level, default 1 + * @return string|null null or file name:line number + */ + public static function getCallerFileLine(int $level = 1): ?string + { + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + // print \CoreLibs\Debug\Support::printAr($traces); + // We should check from top down if unset? + // sets the start point here, and in level two (the sub call) we find this + if (isset($traces[$level])) { + return ($traces[$level]['file'] ?? $traces[$level]['function']) + . ':' . ($traces[$level]['line'] ?? '-'); + } + return null; + } + /** * if there is a need to find out which parent method called a child method, * eg for debugging, this function does this * * call this method in the child method and you get the parent function that called - * @param int $level debug level, default 1 + * @param int $level trace level, default 1 * @return ?string null or the function that called the function * where this method is called */ diff --git a/www/lib/CoreLibs/Logging/Logger/Flag.php b/www/lib/CoreLibs/Logging/Logger/Flag.php new file mode 100644 index 00000000..6fb8fc45 --- /dev/null +++ b/www/lib/CoreLibs/Logging/Logger/Flag.php @@ -0,0 +1,107 @@ + per_date, cannot be used at the same time) + * per_group: for debug level, group per group id (old level) + * per_page: per file name logging + * per_class: log per class + * per_level: per logging level file split +*/ + +declare(strict_types=1); + +namespace CoreLibs\Logging\Logger; + +enum Flag: int +{ + /** all off flag */ + case all_off = 0; + + /** write per run */ + case per_run = 1; + + /** write per date */ + case per_date = 2; + + /** was PER_LEVEL, write per group id (debug) */ + case per_group = 4; + + /** write per page (filename) */ + case per_page = 8; + + /** write per class */ + case per_class = 16; + + /** write per log level name */ + case per_level = 32; + + /** + * get internal name from string value + * + * @param non-empty-string $name + * @return self + */ + public static function fromName(string $name): self + { + return match ($name) { + 'Run', 'run', 'per_run', 'PER_RUN' => self::per_run, + 'Date', 'date', 'per_date', 'PER_DATE' => self::per_date, + 'Group', 'group', 'per_group', 'PER_GROUP' => self::per_group, + 'Page', 'page', 'per_page', 'PER_PAGE' => self::per_page, + 'Class', 'class', 'per_class', 'PER_CLASS' => self::per_class, + 'Level', 'level', 'per_level', 'PER_LEVEL' => self::per_level, + default => self::all_off, + }; + } + + /** + * Get internal name from int value + * + * @param int $value + * @return self + */ + public static function fromValue(int $value): self + { + return self::from($value); + } + + /** + * convert current set level to name (upper case) + * + * @return string + */ + public function getName(): string + { + return strtoupper($this->name); + } + + /** @var int[] */ + public const VALUES = [ + 0, + 1, + 2, + 4, + 8, + 16, + 32, + ]; + + /** @var string[] */ + public const NAMES = [ + 'ALL_OFF', + 'PER_RUN', + 'PER_DATE', + 'PER_GROUP', + 'PER_PAGE', + 'PER_CLASS', + 'PER_LEVEL', + ]; +} + +// __END__ diff --git a/www/lib/CoreLibs/Logging/Logger/Level.php b/www/lib/CoreLibs/Logging/Logger/Level.php new file mode 100644 index 00000000..355dce43 --- /dev/null +++ b/www/lib/CoreLibs/Logging/Logger/Level.php @@ -0,0 +1,216 @@ +getName() to get the standard Monolog name which is full uppercased (e.g. "DEBUG") + * - Use ->toPsrLogLevel() to get the standard PSR-3 name which is full lowercased (e.g. "debug") + * - Use ->toRFC5424Level() to get the standard RFC 5424 value (e.g. 7 for debug, 0 for emergency) + * - Use ->name to get the enum case's name which is capitalized (e.g. "Debug") + * + * To get the internal value for filtering, if the includes/isLowerThan/isHigherThan methods are + * not enough, you can use ->value to get the enum case's integer value. + */ +enum Level: int +{ + /** + * Detailed debug information + */ + case Debug = 100; + + /** + * Interesting events + * + * Examples: User logs in, SQL logs. + */ + case Info = 200; + + /** + * Uncommon events + */ + case Notice = 250; + + /** + * Exceptional occurrences that are not errors + * + * Examples: Use of deprecated APIs, poor use of an API, + * undesirable things that are not necessarily wrong. + */ + case Warning = 300; + + /** + * Runtime errors + */ + case Error = 400; + + /** + * Critical conditions + * + * Example: Application component unavailable, unexpected exception. + */ + case Critical = 500; + + /** + * Action must be taken immediately + * + * Example: Entire website down, database unavailable, etc. + * This should trigger the SMS alerts and wake you up. + */ + case Alert = 550; + + /** + * Urgent alert. + */ + case Emergency = 600; + + /** + * @param value-of|LogLevel::*|'Debug'|'Info'|'Notice'|'Warning'|'Error'|'Critical'|'Alert'|'Emergency' $name + * @return static + */ + public static function fromName(string $name): self + { + return match ($name) { + 'debug', 'Debug', 'DEBUG' => self::Debug, + 'info', 'Info', 'INFO' => self::Info, + 'notice', 'Notice', 'NOTICE' => self::Notice, + 'warning', 'Warning', 'WARNING' => self::Warning, + 'error', 'Error', 'ERROR' => self::Error, + 'critical', 'Critical', 'CRITICAL' => self::Critical, + 'alert', 'Alert', 'ALERT' => self::Alert, + 'emergency', 'Emergency', 'EMERGENCY' => self::Emergency, + }; + } + + /** + * @param value-of $value + * @return static + */ + public static function fromValue(int $value): self + { + return self::from($value); + } + + /** + * Returns true if the passed $level is higher or equal to $this + */ + public function includes(Level $level): bool + { + return $this->value <= $level->value; + } + + public function isHigherThan(Level $level): bool + { + return $this->value > $level->value; + } + + public function isLowerThan(Level $level): bool + { + return $this->value < $level->value; + } + + /** + * Returns the monolog standardized all-capitals name of the level + * + * Use this instead of $level->name which returns the enum case name (e.g. Debug vs DEBUG if you use getName()) + * + * @phan-suppress-next-line PhanTypeMismatchDeclaredReturn + * @return value-of + */ + public function getName(): string + { + return match ($this) { + self::Debug => 'DEBUG', + self::Info => 'INFO', + self::Notice => 'NOTICE', + self::Warning => 'WARNING', + self::Error => 'ERROR', + self::Critical => 'CRITICAL', + self::Alert => 'ALERT', + self::Emergency => 'EMERGENCY', + }; + } + + /** + * Returns the PSR-3 level matching this instance + * + * @phpstan-return \Psr\Log\LogLevel::* + */ + public function toPsrLogLevel(): string + { + return match ($this) { + self::Debug => LogLevel::DEBUG, + self::Info => LogLevel::INFO, + self::Notice => LogLevel::NOTICE, + self::Warning => LogLevel::WARNING, + self::Error => LogLevel::ERROR, + self::Critical => LogLevel::CRITICAL, + self::Alert => LogLevel::ALERT, + self::Emergency => LogLevel::EMERGENCY, + }; + } + + /** + * Returns the RFC 5424 level matching this instance + * + * @phpstan-return int<0, 7> + */ + public function toRFC5424Level(): int + { + return match ($this) { + self::Debug => 7, + self::Info => 6, + self::Notice => 5, + self::Warning => 4, + self::Error => 3, + self::Critical => 2, + self::Alert => 1, + self::Emergency => 0, + }; + } + + public const VALUES = [ + 100, + 200, + 250, + 300, + 400, + 500, + 550, + 600, + ]; + + public const NAMES = [ + 'DEBUG', + 'INFO', + 'NOTICE', + 'WARNING', + 'ERROR', + 'CRITICAL', + 'ALERT', + 'EMERGENCY', + ]; +} + + +// __END__ diff --git a/www/lib/CoreLibs/Logging/Logging.php b/www/lib/CoreLibs/Logging/Logging.php new file mode 100644 index 00000000..d7430ddf --- /dev/null +++ b/www/lib/CoreLibs/Logging/Logging.php @@ -0,0 +1,1319 @@ +>|array{string:array{type:string,type_info?:string,mandatory:true,alias?:string,default:string|bool|Level,deprecated:bool,use?:string}} */ + private const OPTIONS = [ + 'log_folder' => [ + 'type' => 'string', 'mandatory' => true, + 'default' => '', 'deprecated' => false + ], + 'log_file_id' => [ + 'type' => 'string', 'mandatory' => true, 'alias' => 'file_id', + 'default' => '', 'deprecated' => false + ], + 'file_id' => [ + 'type' => 'string', 'mandatory' => false, + 'default' => '', 'deprecated' => true, 'use' => 'log_file_id' + ], + 'log_level' => [ + 'type' => 'instance', + 'type_info' => '\CoreLibs\Logging\Logger\Level', + 'mandatory' => false, + 'default' => Level::Debug, + 'deprecated' => false + ], + // options + 'log_per_run' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'log_per_date' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'log_per_group' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'log_per_page' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'log_per_class' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'log_per_level' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => false + ], + 'print_file_date' => [ + 'type' => 'bool', 'mandatory' => false, + 'default' => false, 'deprecated' => true, 'use' => 'log_per_date' + ], + ]; + + // options + /** @var array */ + private $options = []; + + /** @var Level set level */ + private $log_level; + + // page and host name + /** @var string */ + private $host_name; + /** @var int */ + private $host_port; + /** @var string unique ID set on class init and used in logging as prefix */ + private $running_uid = ''; + + // log file name + /** @var string */ + private $log_folder = ''; + /** @var string a alphanumeric name that has to be set as global definition */ + private $log_file_id = ''; + /** @var string log file name extension */ + private $log_file_name_ext = 'log'; + /** @var string log file name with folder, for actual writing */ + private $log_file_name = ''; + /** @var int set in bytes */ + private $log_max_filesize = 0; + /** @var string used if no log id set or found */ + private $log_file_prefix = 'error_msg'; + /** @var string */ + private $log_print_file = '{LOGID}{LEVEL}{GROUP}{CLASS}{PAGENAME}{DATE_RUNID}'; + /** @var string a unique ID set only once for call derived from this class */ + private $log_file_unique_id = ''; + /** @var string Y-m-d file in file name */ + private $log_file_date = ''; + + /** + * 1: create a new log file per run (time stamp + unique ID) + * 2: add Y-m-d and do automatic daily rotation + * 4: split per group (first parameter in debug call, group id, former level) + * 8: split log per called file + * 16: split log per class + * 32: split log per set log level + */ + /** @var int bitwise set for log flags */ + private $log_flags = 0; + /** @var array valid log flag names */ + private $log_valid_flags = [ + 'log_per_run' => Flag::per_run, + 'log_per_date' => Flag::per_date, + 'log_per_group' => Flag::per_group, + 'log_per_page' => Flag::per_page, + 'log_per_class' => Flag::per_class, + // not before it was PER_GROUP type + 'log_per_level' => Flag::per_level, + // below are old & deprecated + 'print_file_date' => Flag::per_date, + ]; + + /** + * Init logger + * + * options array layout + * - log_folder: + * - log_file_id / file_id (will be deprecated): + * - log_level: + * + * - log_per_run: + * - log_per_date: (was print_file_date) + * - log_per_group + * - log_per_page: + * - log_per_class: + * - log_per_level: + * + * @param array $options Array with settings options + */ + public function __construct(array $options = []) + { + // options chekc + // must set values + // * path + // * file id + // * log level + $this->optionsCheck($options); + + // set log level + $this->initLogLevel(); + // set log folder from options + $this->initLogFolder(); + // set per run UID for logging + $this->running_uid = Uids::uniqIdShort(); + // set host name + $this->initHostName(); + // set file id + $this->initLogFileId(); + // set max file size for logging, 0 = no limit + $this->setLogMaxFileSize($this->options['log_max_file_size'] ?? 0); + // set flags and values needed for those flags + $this->initLogFlagsAndValues(); + } + + // ********************************************************************* + // PRIVATE METHODS + // ********************************************************************* + + /** + * Undocumented function + * + * @param array $options + * @return bool + */ + private function optionsCheck(array $options): bool + { + // make sure only valid ones are in the options list, + // drop all others + // check for missing (trigger warning?) + foreach (self::OPTIONS as $name => $settings) { + // first deprecation warnings + if (isset($options[$name]) && $settings['deprecated']) { + trigger_error( + 'options: "' . $name . '" is deprecated use: "' + . ($settings['use'] ?? 'NO_REPLACEMENT') . '".', + E_USER_DEPRECATED + ); + } + // if mandatory and not set -> warning + if ( + $settings['mandatory'] && !isset($options[$name]) && + empty($settings['alias']) + ) { + throw new \InvalidArgumentException( + 'Missing mandatory option: "' . $name . '"', + E_USER_WARNING + ); + } elseif ( + // if not mandatory and not set -> default + !$settings['mandatory'] && !isset($options[$name]) + ) { + $this->options[$name] = $settings['default']; + } else { + // else set from options + $this->options[$name] = $options[$name] ?? $settings['default']; + } + // check valid type (only type not content) + switch ($settings['type']) { + case 'bool': + if (!is_bool($this->options[$name])) { + throw new \InvalidArgumentException( + 'Option: "' . $name . '" is not of type bool', + E_USER_ERROR + ); + } + break; + case 'string': + if (!is_string($this->options[$name])) { + throw new \InvalidArgumentException( + 'Option: "' . $name . '" is not of type string', + E_USER_ERROR + ); + } + break; + case 'instance': + if ( + empty($settings['type_info']) || + !$this->options[$name] instanceof $settings['type_info'] + ) { + throw new \InvalidArgumentException( + 'Option: "' . $name . '" is not of instance ' + . ($settings['type_info'] ?? 'NO INSTANCE DEFINED'), + E_USER_ERROR + ); + } + break; + } + } + return true; + } + + /** + * init log level, just a wrapper to auto set from options + * + * @return void + */ + private function initLogLevel() + { + // if this is not a valid instance of Level Enum then set to Debug + if ( + empty($this->options['log_level']) || + !$this->options['log_level'] instanceof Level + ) { + $this->options['log_level'] = Level::Debug; + } + $this->setLoggingLevel($this->options['log_level']); + } + + /** + * Set the log folder + * If folder is not writeable the script will throw an E_USER_ERROR + * + * @return bool True on proper set, False on not proper set folder + */ + private function initLogFolder(): bool + { + $status = true; + // set log folder from options + $log_folder = $this->options['log_folder'] ?? ''; + // legacy flow, check must set constants + if (empty($log_folder) && defined('BASE') && defined('LOG')) { + /** @deprecated Do not use this anymore, define path on class load */ + trigger_error( + 'options: log_folder must be set. Setting via BASE and LOG constants is deprecated', + E_USER_DEPRECATED + ); + // make sure this is writeable, else skip + $log_folder = BASE . LOG; + $status = false; + } + // fallback + notice + if (empty($log_folder)) { + /* trigger_error( + 'option log_folder is empty. fallback to: ' . getcwd(), + E_USER_NOTICE + ); */ + $log_folder = getcwd() . DIRECTORY_SEPARATOR; + $status = false; + } + // if folder is not writeable, abort + if (!$this->setLogFolder($log_folder)) { + throw new InvalidArgumentException( + 'Folder: "' . $log_folder . '" is not writeable for logging', + E_USER_ERROR + ); + } + return $status; + } + + /** + * Set the hostname and port + * If port is not defaul 80 it will be added to the host name + * + * @return void + */ + private function initHostName(): void + { + // set host name + list($this->host_name , $this->host_port) = System::getHostName(); + // add port to host name if not port 80 + if ($this->host_port != 80) { + $this->host_name .= ':' . $this->host_port; + } + } + + /** + * set log file prefix id + * + * @return bool + */ + private function initLogFileId(): bool + { + $status = true; + + // alert of log_file_id and file_id is, log_file_id is prefered + if ( + !empty($this->options['log_file_id']) && + !empty($this->options['file_id']) + ) { + trigger_error( + 'options: both log_file_id and log_id are set at the same time, will use log_file_id', + E_USER_WARNING + ); + $this->options['log_file_id'] = $this->options['file_id']; + unset($this->options['file_id']); + } + if ( + empty($this->options['log_file_id']) && + !empty($this->options['file_id']) + ) { + // will trigger deprecation in future + $this->options['log_file_id'] = $this->options['file_id']; + unset($this->options['file_id']); + } + + // can be overridden with basicSetLogFileId later + if (!empty($this->options['log_file_id'])) { + $this->setLogFileId($this->options['log_file_id']); + } elseif (!empty($GLOBALS['LOG_FILE_ID'])) { + /** @deprecated Do not use this anymore, define file_id on class load */ + trigger_error( + 'options: log_file_id must be set. Setting via LOG_FILE_ID global variable is deprecated', + E_USER_DEPRECATED + ); + $status = false; + // legacy flow, should be removed and only set via options + $this->setLogFileId($GLOBALS['LOG_FILE_ID']); + } else { + // auto set (should be deprecated in future) + $this->setLogFileId( + str_replace(':', '-', $this->host_name) . '_' + . str_replace('\\', '-', Support::getCallerClass()) + ); + } + if (empty($this->getLogFileId())) { + throw new InvalidArgumentException( + 'LogFileId: no log file id set', + E_USER_ERROR + ); + } + return $status; + } + + /** + * set flags from options and option flags connection internal settings + * + * @return void + */ + private function initLogFlagsAndValues(): void + { + // first set all flags + foreach ($this->log_valid_flags as $log_flag => $log_flag_key) { + if (empty($this->options[$log_flag])) { + continue; + } + $this->setLogFlag($log_flag_key); + } + // init per run uid + if ($this->getLogFlag(Flag::per_run)) { + $this->setLogUniqueId(); + } elseif ($this->getLogFlag(Flag::per_date)) { + // init file date + $this->log_file_date = date('Y-m-d'); + } + } + + /** + * check if set log level is equal or higher than + * requested one + * + * @param Level $level + * @return bool True to allow write, False for not + */ + private function checkLogLevel(Level $level): bool + { + return $this->log_level->includes($level); + } + + /** + * Build the file name for writing + * + * @param Level $level Request log level + * @param string $group_id Debug level group name id + * @return string + */ + private function buildLogFileName(Level $level, string $group_id = ''): string + { + // init base file path + $fn = $this->log_print_file . '.' . $this->log_file_name_ext; + // log ID prefix settings, if not valid, replace with empty + if (!empty($this->log_file_id)) { + $rpl_string = $this->log_file_id; + } else { + $rpl_string = $this->log_file_prefix; + } + $fn = str_replace('{LOGID}', $rpl_string, $fn); // log id (like a log file prefix) + + $rpl_string = !$this->getLogFlag(Flag::per_level) ? '' : + '_' . $level->getName(); + $fn = str_replace('{LEVEL}', $rpl_string, $fn); // create output filename + + // write per level + $rpl_string = !$this->getLogFlag(Flag::per_group) ? '' : + // normalize level, replace all non alphanumeric characters with - + '_' . ( + // if return is only - then set error string + preg_match( + "/^-+$/", + $level_string = preg_replace("/[^A-Za-z0-9-_]/", '-', $group_id) ?? '' + ) ? + 'INVALID-LEVEL-STRING' : + $level_string + ); + $fn = str_replace('{GROUP}', $rpl_string, $fn); // create output filename + // set per class, but don't use get_class as we will only get self + $rpl_string = !$this->getLogFlag(Flag::per_class) ? '' : '_' + // set sub class settings + . str_replace('\\', '-', Support::getCallerClass()); + $fn = str_replace('{CLASS}', $rpl_string, $fn); // create output filename + + // if request to write to one file + $rpl_string = !$this->getLogFlag(Flag::per_page) ? + '' : + '_' . System::getPageName(System::NO_EXTENSION); + $fn = str_replace('{PAGENAME}', $rpl_string, $fn); // create output filename + + // if run id, we auto add ymd, so we ignore the log file date + if ($this->getLogFlag(Flag::per_run)) { + $rpl_string = '_' . $this->getLogUniqueId(); // add 8 char unique string + } elseif ($this->getLogFlag(Flag::per_date)) { + $rpl_string = '_' . $this->getLogDate(); // add date to file + } else { + $rpl_string = ''; + } + $fn = str_replace('{DATE_RUNID}', $rpl_string, $fn); // create output filename + $this->log_file_name = $fn; + + return $fn; + } + + /** + * writes error msg data to file for current level + * + * @param Level $level Log Level we wnat to write to + * @param string|Stringable $message Log message to write + * @param string $group_id A group + * @return bool True if message written, False if not + */ + private function writeErrorMsg( + Level $level, + string|\Stringable $message, + string $group_id = '' + ): bool { + // only write if write is requested + if (!$this->checkLogLevel($level)) { + return false; + } + + // build logging file name + // fn is log folder + file name + $fn = $this->log_folder . $this->buildLogFileName($level, $group_id); + + // write to file + // first check if max file size is is set and file is bigger + if ( + $this->log_max_filesize > 0 && + (filesize($fn) > $this->log_max_filesize) + ) { + // for easy purpose, rename file only to attach timestamp, no sequence numbering + rename($fn, $fn . '.' . date("YmdHis")); + } + $fp = fopen($fn, 'a'); + if ($fp === false) { + echo ""; + return false; + } + fwrite($fp, $message . "\n"); + fclose($fp); + return true; + } + + /** + * Prepare the log message with all needed info blocks: + * [timestamp] [host name] [file path + file] [running uid] {class} - message + * + * @param string $level_str Log level we will write to + * @param string|Stringable $message The message to write + * @param mixed[] $context Any additional info we want to attach in any format + * @param string $group_id A group id, only used in DEBUG level, + * if empty set to log level + * @return string + */ + private function prepareLog( + string $level_str, + string|\Stringable $message, + array $context = [], + string $group_id = '', + ): string { + // get the last class entry and wrie that + $class = Support::getCallerClass(); + // get timestamp + $timestamp = Support::printTime(); + + // if group id is empty replace it with current level + $group_str = $level_str; + if (!empty($group_id)) { + $group_str .= ':' . $group_id; + } + // additional context + $context_str = ''; + if ($context != []) { + // TODO this here has to be changed to something better + $context_str = ' ' . print_r($context, true); + } + // build log string + return '[' . $timestamp . '] ' + . '[' . $this->host_name . '] ' + . '[' . System::getPageName(System::FULL_PATH) . '] ' + . '[' . $this->running_uid . '] ' + . '{' . $class . '} ' + . '<' . strtoupper($group_str) . '> ' + . $message + . $context_str; + } + + // ********************************************************************* + // PUBLIC STATIC METHJODS + // ********************************************************************* + + /** + * set the log level + * + * from Monolog\Logger + * + * @param string|int|Level $level + * @return Level + */ + public static function processLogLevel(string|int|Level $level): Level + { + if ($level instanceof Level) { + return $level; + } + + if (\is_string($level)) { + if (\is_numeric($level)) { + $levelEnum = Level::tryFrom((int)$level); + if ($levelEnum === null) { + throw new InvalidArgumentException( + 'Level "' . $level . '" is not defined, use one of: ' + /** @phan-suppress-next-line PhanUselessBinaryAddRight */ + . implode(', ', Level::NAMES + Level::VALUES) + ); + } + + return $levelEnum; + } + + // Contains first char of all log levels and avoids using strtoupper() which may have + // strange results depending on locale (for example, "i" will become "İ" in Turkish locale) + $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') + . strtolower(substr($level, 1)); + if (defined(Level::class . '::' . $upper)) { + return constant(Level::class . '::' . $upper); + } + + throw new InvalidArgumentException( + 'Level "' . $level . '" is not defined, use one of: ' + /** @phan-suppress-next-line PhanUselessBinaryAddRight */ + . implode(', ', Level::NAMES + Level::VALUES) + ); + } + + $levelEnum = Level::tryFrom($level); + if ($levelEnum === null) { + throw new InvalidArgumentException( + 'Level "' . var_export($level, true) . '" is not defined, use one of: ' + /** @phan-suppress-next-line PhanUselessBinaryAddRight */ + . implode(', ', Level::NAMES + Level::VALUES) + ); + } + + return $levelEnum; + } + + // ********************************************************************* + // PUBLIC METHODS + // ********************************************************************* + + // **** GET/SETTER + + // log level set and get + + /** + * set new log level + * + * @param string|int|Level $level + * @return void + */ + public function setLoggingLevel(string|int|Level $level): void + { + $this->log_level = $this->processLogLevel($level); + } + + /** + * return current set log level + * + * @return Level + */ + public function getLoggingLevel(): Level + { + return $this->log_level; + } + + /** + * this is for older JS_DEBUG flags + * + * @return bool True, we are at debug level + */ + public function getJsDebug(): bool + { + return $this->log_level === Level::Debug ? true : false; + } + + // log file id set (file name prefix) + + /** + * sets the internal log file prefix id + * string must be a alphanumeric string + * + * @param string $string log file id string value + * @return bool + */ + public function setLogFileId(string $string): bool + { + if (!preg_match("/^[\w\.\-]+$/", $string)) { + return false; + } + $this->log_file_id = $string; + return true; + } + + /** + * return current set log file id + * + * @return string + */ + public function getLogFileId(): string + { + return $this->log_file_id; + } + + // log unique id set (for per run) + + /** + * Sets a unique id based on current date (y/m/d, h:i:s) and a unique id (8 chars) + * if override is set to true it will be newly set, else if already set nothing changes + * + * @param bool $override True to force new set + * @return void + */ + public function setLogUniqueId(bool $override = false): void + { + if (empty($this->log_file_unique_id) || $override == true) { + $this->log_file_unique_id = + date('Y-m-d_His') . '_U_' + . substr(hash('sha1', uniqid((string)mt_rand(), true)), 0, 8); + } + } + + /** + * Return current set log file unique id, + * empty string for not set + * + * @return string + */ + public function getLogUniqueId(): string + { + return $this->log_file_unique_id; + } + + // general log date + + /** + * set the log file date to Y-m-d + * must be set if log_per_date is set + * + * @return void + */ + public function setLogDate(): void + { + $this->log_file_date = date('Y-m-d'); + } + + /** + * get the current set log file_date + * + * @return string + */ + public function getLogDate(): string + { + return $this->log_file_date; + } + + // general flag set + + /** + * set one of the basic flags + * + * @param Flag $flag flag level to set + * @return void + */ + public function setLogFlag(Flag $flag): void + { + $this->log_flags |= $flag->value; + } + + /** + * unset given from the log flags + * + * @param Flag $flag flag level to unset + * @return void + */ + public function unsetLogFlag(Flag $flag): void + { + $this->log_flags &= ~$flag->value; + } + + /** + * check if a given flag is set + * + * @param Flag $flag + * @return bool + */ + public function getLogFlag(Flag $flag): bool + { + if ($this->log_flags & $flag->value) { + return true; + } + return false; + } + + /** + * Return all set log flags as int + * + * @return int + */ + public function getLogFlags(): int + { + return $this->log_flags; + } + + // log folder/file + + /** + * set new log folder, check that folder is writeable + * If not setable keep older log folder setting + * + * @param string $log_folder Folder to set + * @return bool If not setable, return false + */ + public function setLogFolder(string $log_folder): bool + { + if (!is_writeable($log_folder)) { + return false; + } + // check if log_folder has a trailing / + if (substr($log_folder, -1, 1) != DIRECTORY_SEPARATOR) { + $log_folder .= DIRECTORY_SEPARATOR; + } + $this->log_folder = $log_folder; + return true; + } + + /** + * get current set log folder + * + * @return string + */ + public function getLogFolder(): string + { + return $this->log_folder; + } + + // note that set log filder is dynamic during log write + + /** + * get last set log file name + * + * @return string + */ + public function getLogFile(): string + { + return $this->log_file_name; + } + + // max log file size + + /** + * set mag log file size + * + * @param int $file_size Set max file size in bytes, 0 for no limit + * @return bool False for invalid number + */ + public function setLogMaxFileSize(int $file_size): bool + { + if ($file_size < 0) { + return false; + } + if ($file_size < self::MIN_LOG_MAX_FILESIZE) { + return false; + } + $this->log_max_filesize = $file_size; + return true; + } + + /** + * Return current set log max file size in bytes + * + * @return int Max size in bytes, 0 for no limit + */ + public function getLogMaxFileSize(): int + { + return $this->log_max_filesize; + } + + // ********************************************************************* + // OPTIONS CALLS + // ********************************************************************* + + /** + * get option + * + * @param string $option_key Which option key to search + * @return string|bool|int|null Returns null on not found + */ + public function getOption(string $option_key): string|bool|int|null + { + return $this->options[$option_key] ?? null; + } + + // ********************************************************************* + // MAIN CALLS + // ********************************************************************* + + /** + * DEBUG: 100 + * + * write debug data to error_msg array + * + * @param string $group_id id for error message, groups messages together + * @param string|Stringable $message the actual error message + * @param string $prefix Attach some block before $string. + * Will not be stripped even + * when strip is true + * if strip is false, recommended to add that to $string + * @param mixed[] $context + * @return bool True if logged, false if not logged + */ + public function debug( + string $group_id, + string|\Stringable $message, + string $prefix = '', + array $context = [] + ): bool { + return $this->writeErrorMsg( + $this->log_level, + $this->prepareLog( + Level::Debug->getName(), + $prefix . $message, + $context, + $group_id + ), + $group_id + ); + } + + /** + * INFO: 200 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function info(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Info, + $this->prepareLog( + Level::Info->getName(), + $message, + $context, + ) + ); + } + + /** + * NOTICE: 250 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function notice(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Notice, + $this->prepareLog( + Level::Notice->getName(), + $message, + $context, + ) + ); + } + + /** + * WARNING: 300 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function warning(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Warning, + $this->prepareLog( + Level::Warning->getName(), + $message, + $context, + ) + ); + } + + /** + * ERROR: 400 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function error(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Error, + $this->prepareLog( + Level::Error->getName(), + $message, + $context, + ) + ); + } + + /** + * CTRITICAL: 500 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function critical(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Critical, + $this->prepareLog( + Level::Critical->getName(), + $message, + $context, + ) + ); + } + + /** + * ALERT: 550 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function alert(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Alert, + $this->prepareLog( + Level::Alert->getName(), + $message, + $context, + ) + ); + } + + /** + * EMERGENCY: 600 + * + * @param string|Stringable $message + * @param mixed[] $context + * @return bool + */ + public function emergency(string|\Stringable $message, array $context = []): bool + { + return $this->writeErrorMsg( + Level::Emergency, + $this->prepareLog( + Level::Emergency->getName(), + $message, + $context, + ) + ); + } + + // ********************************************************************* + // DEPRECATED SUPPORT CALLS + // ********************************************************************* + + // legacy, but there are too many implemented + + /** + * A replacement for the \CoreLibs\Debug\Support::printAr + * But this does not wrap it in

+	 * Do not use this without using it in a string in debug function
+	 *
+	 * @param  array $a Array to format
+	 * @return string          print_r formated
+	 */
+	public function prAr(array $a): string
+	{
+		return Support::printArray($a, true);
+	}
+
+	/**
+	 * Convert bool value to string value
+	 *
+	 * @param  bool   $bool  Bool value to be transformed
+	 * @param  string $true  Override default string 'true'
+	 * @param  string $false Override default string 'false'
+	 * @return string        $true or $false string for true/false bool
+	 */
+	public function prBl(
+		bool $bool,
+		string $true = 'true',
+		string $false = 'false'
+	): string {
+		return Support::printBool($bool, '', $true, $false, true);
+	}
+
+	/**
+	 * Dump data as string without html
+	 *
+	 * @param  mixed  $data  Any data
+	 * @param  bool   $strip If false, do not strip, default is true
+	 * @return string        Output data for debug
+	 */
+	public function dV(mixed $data, bool $strip = true): string
+	{
+		return Support::dumpVar($data, $strip);
+	}
+
+	/**
+	 * Export var data to string
+	 *
+	 * @param  mixed  $data
+	 * @return string
+	 */
+	public function eV(mixed $data): string
+	{
+		return Support::exportVar($data, true);
+	}
+
+	// *********************************************************************
+	// DEPRECATED METHODS
+	// *********************************************************************
+
+	/**
+	 * Everything below here is deprecated and will be removed
+	 */
+
+	/**
+	 * Temporary method to read all class variables for testing purpose
+	 *
+	 * @param  string $name what variable to return
+	 * @return mixed        can be anything, bool, string, int, array
+	 * @deprecated Use either log->getOption or log->get[Content] to fetch info
+	 */
+	public function getSetting(string $name): mixed
+	{
+		// for debug purpose only
+		return $this->{$name};
+	}
+
+	/**
+	 * sets the internal log file prefix id
+	 * string must be a alphanumeric string
+	 * if non valid string is given it returns the previous set one only
+	 *
+	 * @param  string $string log file id string value
+	 * @return string        returns the set log file id string
+	 * @deprecated Use Debug\Logging->setLogId() and Debug\Logging->getLogId()
+	 */
+	public function basicSetLogId(string $string): string
+	{
+		$this->setLogFileId($string);
+		return $this->getLogFileId();
+	}
+
+	/**
+	 * old name for setLogLevel
+	 *
+	 * @param  string $type  debug, echo, print
+	 * @param  string $flag  on/off
+	 *         array  $array of levels to turn on/off debug
+	 * @return bool          Return false if type or flag is invalid
+	 * @deprecated Use setLogLevel
+	 */
+	public function debugFor(string $type, string $flag): bool
+	{
+		trigger_error(
+			'debugFor() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * set log level settings for All types
+	 * if invalid type, skip
+	 *
+	 * @param  string $type Type to get: debug, echo, print
+	 * @param  bool   $set  True or False
+	 * @return bool         Return false if type invalid
+	 * @deprecated Log levels (group id) are no longer supported
+	 */
+	public function setLogLevelAll(string $type, bool $set): bool
+	{
+		trigger_error(
+			'setLogLevelAll() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * get the current log level setting for All level blocks
+	 *
+	 * @param  string $type Type to get: debug, echo, print
+	 * @return bool         False on failure, or the boolean flag from the all var
+	 * @deprecated Log levels (group id) are no longer supported
+	 */
+	public function getLogLevelAll(string $type): bool
+	{
+		trigger_error(
+			'getLogLevelAll() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * passes list of level names, to turn on debug
+	 * eg $foo->debugFor('print', 'on', ['LOG', 'DEBUG', 'INFO']);
+	 *
+	 * @param  string        $type     debug, echo, print
+	 * @param  string        $flag     on/off
+	 * @param  array  $debug_on Array of levels to turn on/off debug
+	 *                                 To turn off a level set 'Level' => false,
+	 *                                 If not set, switches to on
+	 * @return bool          Return false if type or flag invalid
+	 *                       also false if debug array is empty
+	 * @deprecated Log levels (group id) are no longer supported
+	 */
+	public function setLogLevel(string $type, string $flag, array $debug_on): bool
+	{
+		trigger_error(
+			'setLogLevel() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * return the log level for the array type normal and not (disable)
+	 *
+	 * @param  string      $type  debug, echo, print
+	 * @param  string      $flag  on/off
+	 * @param  string|null $level if not null then check if this array entry is set
+	 *                            else return false
+	 * @return array|bool  if $level is null, return array, else boolean true/false
+	 * @deprecated Log levels (group id) are no longer supported
+	 */
+	public function getLogLevel(string $type, string $flag, ?string $level = null): array|bool
+	{
+		trigger_error(
+			'getLogLevel() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * set flags for per log level type
+	 * - level: set per sub group level
+	 * - class: split by class
+	 * - page: split per page called
+	 * - run: for each run
+	 *
+	 * @param  string $type Type to get: level, class, page, run
+	 * @param  bool   $set  True or False
+	 * @return bool         Return false if type invalid
+	 * @deprecated Set flags with setLogFlag
+	 */
+	public function setLogPer(string $type, bool $set): bool
+	{
+		trigger_error(
+			'setLogPer() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	/**
+	 * return current set log per flag in bool
+	 *
+	 * @param  string $type Type to get: level, class, page, run
+	 * @return bool         True of false for turned on or off
+	 * @deprecated Get flags with setLogFlag
+	 */
+	public function getLogPer(string $type): bool
+	{
+		trigger_error(
+			'getLogPer() is deprecated',
+			E_USER_DEPRECATED
+		);
+		return false;
+	}
+
+	// *********************************************************************
+	// DEBUG METHODS
+	// *********************************************************************
+
+	/**
+	 * only for debug
+	 *
+	 * @return void
+	 */
+	public function logger2Debug(): void
+	{
+		print "Options: " . Support::dumpVar($this->options) . "
"; + print "OPT set level: " . $this->getLoggingLevel()->getName() . "
"; + $this->setLoggingLevel(Level::Info); + print "NEW set level: " . $this->getLoggingLevel()->getName() . "
"; + foreach ( + [ + Level::Debug, Level::Info, Level::Notice, Level::Warning, + Level::Error, Level::Critical, Level::Alert, Level::Emergency + ] as $l + ) { + if ($this->log_level->isHigherThan($l)) { + print "L: " . $this->log_level->getName() . " > " . $l->getName() . "
"; + } + if ($this->log_level->includes($l)) { + print "L: " . $this->log_level->getName() . " <= " . $l->getName() . "
"; + } + if ($this->log_level->isLowerThan($l)) { + print "L: " . $this->log_level->getName() . " < " . $l->getName() . "
"; + } + echo "
"; + } + // back to options level + $this->initLogLevel(); + print "OPT set level: " . $this->getLoggingLevel()->getName() . "
"; + } +} + +// __END__ diff --git a/www/lib/CoreLibs/Output/Form/Generate.php b/www/lib/CoreLibs/Output/Form/Generate.php index 90daccc8..6ec76223 100644 --- a/www/lib/CoreLibs/Output/Form/Generate.php +++ b/www/lib/CoreLibs/Output/Form/Generate.php @@ -219,6 +219,7 @@ declare(strict_types=1); namespace CoreLibs\Output\Form; use CoreLibs\Get\System; +use CoreLibs\Debug\Support; class Generate extends \CoreLibs\DB\Extended\ArrayIO { @@ -297,7 +298,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO /** @var \CoreLibs\Language\L10n */ public $l; // log - /** @var \CoreLibs\Debug\Logging */ + /** @var \CoreLibs\Logging\Logging */ public $log; // now some default error msgs (english) @@ -308,7 +309,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO * construct form generator * * @param array $db_config db config array, mandatory - * @param \CoreLibs\Debug\Logging $log Logging class + * @param \CoreLibs\Logging\Logging $log Logging class * @param \CoreLibs\Language\L10n $l10n l10n language class * @param array $login_acl Login ACL array, * at least base/admin should be set @@ -319,7 +320,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO */ public function __construct( array $db_config, - \CoreLibs\Debug\Logging $log, + \CoreLibs\Logging\Logging $log, \CoreLibs\Language\L10n $l10n, array $login_acl, ?array $table_arrays = null, @@ -327,7 +328,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO // init logger if not set $this->log = $log; // don't log per class - $this->log->setLogPer('class', false); + $this->log->unsetLogFlag(\CoreLibs\Logging\Logger\Flag::per_class); // init the language class $this->l = $l10n; // parse and read, legacy stuff @@ -2618,7 +2619,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO } // add lost error ones $this->log->debug('ERROR', 'P: ' . $data['prefix'] . ', ' - . $this->log->prAr($_POST['ERROR'][$data['prefix']] ?? [])); + . Support::prAr($_POST['ERROR'][$data['prefix']] ?? [])); if ($this->error && !empty($_POST['ERROR'][$data['prefix']])) { $prfx = $data['prefix']; // short $_post_data = []; diff --git a/www/lib/Error.Handling.php b/www/lib/Error.Handling.php index b7933ae8..83bbf454 100644 --- a/www/lib/Error.Handling.php +++ b/www/lib/Error.Handling.php @@ -32,8 +32,13 @@ function MyErrorHandler( int $line, array $context = [] ): bool { - /** @phpstan-ignore-next-line cannot check show all errors constant */ - if (!(error_reporting() & $type) && SHOW_ALL_ERRORS === false) { + if (!defined('SHOW_ALL_ERRORS')) { + return false; + } + if ( + !(error_reporting() & $type) && + SHOW_ALL_ERRORS === false + ) { // This error code is not included in error_reporting return false; } diff --git a/www/lib/Test/DB/TestDB.php b/www/lib/Test/DB/TestDB.php index 4846f2d0..f44d49d0 100644 --- a/www/lib/Test/DB/TestDB.php +++ b/www/lib/Test/DB/TestDB.php @@ -18,10 +18,10 @@ class TestDB /** * Undocumented function * - * @param \CoreLibs\Debug\Logging $log + * @param \CoreLibs\Logging\Logging $log */ public function __construct( - \CoreLibs\Debug\Logging $log + \CoreLibs\Logging\Logging $log ) { $this->config = [ 'db_name' => $_ENV['DB_NAME_TEST'] ?? '', diff --git a/www/lib/Test/Test.php b/www/lib/Test/Test.php index b5033ae5..6f788c84 100644 --- a/www/lib/Test/Test.php +++ b/www/lib/Test/Test.php @@ -24,7 +24,7 @@ class Test private $test_db; public function __construct( - \CoreLibs\Debug\Logging $log + \CoreLibs\Logging\Logging $log ) { // calls all tests $this->testPrivate();