Compare commits

..

2 Commits

Author SHA1 Message Date
0722057eaa Update Logger 2025-04-12 20:37:20 +02:00
0901172ec6 Add CLI Support 2025-02-16 22:20:39 +01:00

View File

@ -2,10 +2,10 @@
/**
* @author gnilebein
* @since March 10, 2022
* @since March 12, 2025
* @link https://gitea.gnilebein.de/gnilebein/Simple-PHP-Logger
* @license MIT
* @version 1.0.0
* @version 1.1.0
*
* Description:
* The simple php logger is a single-file logwriter with the features of:
@ -20,6 +20,15 @@
class Logger
{
/**
* Prüft, ob das Skript in der CLI läuft
* @return bool
*/
protected static function isCLI()
{
return PHP_SAPI === 'cli';
}
/**
* $log_file - path and log file name
* @var string
@ -39,7 +48,8 @@ class Logger
protected static $options = [
'dateFormat' => 'd-M-Y',
'logFormat' => 'H:i:s d-M-Y',
'logFileName' => 'log'
'logFileName' => 'log',
'displayOutput' => false // NEU: Steuerung der Ausgabe auf Konsole oder Browser
];
private static $instance;
@ -269,6 +279,16 @@ class Logger
// Write time, url, & message to end of file
fwrite(static::$file, "{$timeLog}{$pathLog}{$lineLog}: {$severityLog} - {$messageLog} {$contextLog}" . PHP_EOL);
// Falls displayOutput aktiv ist, log auch ausgeben
if (!empty(static::$options['displayOutput']) && static::$options['displayOutput'] === true) {
// Für CLI oder Web passend ausgeben
if (static::isCLI()) {
echo "{$timeLog}{$pathLog}{$lineLog}: {$severityLog} - {$messageLog} {$contextLog}" . PHP_EOL;
} else {
echo "<pre>{$timeLog}{$pathLog}{$lineLog}: {$severityLog} - {$messageLog} {$contextLog}</pre>";
}
}
// Close file stream
static::closeFile();
}
@ -295,19 +315,17 @@ class Logger
}
/**
* Convert absolute path to relative url (using UNIX directory seperators)
*
* E.g.:
* Input: D:\development\htdocs\public\todo-list\index.php
* Output: localhost/todo-list/index.php
*
* @param string Absolute directory/path of file which should be converted to a relative (url) path
* @return string Relative path
* Konvertiert einen absoluten Pfad in einen relativen (unter Berücksichtigung von CLI)
*/
public static function absToRelPath($pathToConvert)
{
if (static::isCLI()) {
return $pathToConvert; // In CLI einfach den absoluten Pfad zurückgeben
}
$pathAbs = str_replace(['/', '\\'], '/', $pathToConvert);
$documentRoot = str_replace(['/', '\\'], '/', $_SERVER['DOCUMENT_ROOT']);
$documentRoot = str_replace(['/', '\\'], '/', $_SERVER['DOCUMENT_ROOT'] ?? '');
return $_SERVER['SERVER_NAME'] . str_replace($documentRoot, '', $pathAbs);
}