matrix-register/lib/logger.php
2021-03-01 16:56:53 +01:00

74 lines
1.8 KiB
PHP

<?php
/**
* file: logger.php
* date: 01.03.2021
* author: bernd@nr18.space
* desc: Simpler Logger
*/
class Logger {
/**
* Einfache Klasse zum Loggen von Nachrichten. Schreibt seine
* Nachrichten in eine Datei. Eleganter wäre ein Weiterreichen an den
* Logging-Daemon des Betriebssystems.
* TODO: Er ist wenig Fehlertolerant. Es wird nicht geprüft, ob der
* angefragte Key im Array existiert.
*/
private $levelnumbers = array(
"ERROR" => 10,
"WARN" => 20,
"INFO" => 30,
"DEBUG" => 40,
);
public $loglevel = "INFO";
private $logfile = "log/register.log";
private $app = "matrix-register";
public function e(string $msg) {
$this->logMsg("ERROR", $msg);
}
public function w(string $msg) {
$this->logMsg("WARN", $msg);
}
public function i(string $msg) {
$this->logMsg("INFO", $msg);
}
public function d(string $msg) {
$this->logMsg("DEBUG", $msg);
}
public function setLogLevel(string $level) {
if (array_key_exists($level, $this->levelnumbers) === true) {
$this->loglevel = $level;
$this->writeLog("INFO", "Loglevel set to {$level}");
} else {
$this->writeLog("WARN", "{$level} is not a valid loglevel.");
}
}
private function logMsg(string $label, string $msg) {
$msglevel = $this->levelnumbers[$label];
$loglevel = $this->levelnumbers[$this->loglevel];
if ($loglevel >= $msglevel) {
$this->writeLog($label, $msg);
}
}
private function writeLog(string $label, string $msg) {
$app = $this->app;
$file = $this->logfile;
error_log(date("[Y-m-d H:i:s]")." [".$label."] [".$app."] ".$msg."\n", 3, $file);
}
}
?>