matrix-register/lib/logger.php

114 lines
2.7 KiB
PHP

<?php
/**
* file: logger.php
* date: 01.03.2021
* author: bernd@nr18.space
* desc: Simpler Logger
*/
if (!defined('INCLUDES_ALLOWED'))
die('Access denied.');
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.
*/
public $loglevel = LOG_INFO;
private $app = "matrix-register";
private $logopen = false;
public function __construct() {
if (openlog($this->app, LOG_PID | LOG_PERROR , LOG_SYSLOG) === true) {
$this->logopen = true;
}
}
public function __destruct() {
$this->logopen = false;
closelog();
}
public function a(string $msg) {
$this->logMsg(LOG_ALERT, $msg);
}
public function c(string $msg) {
$this->logMsg(LOG_CRIT, $msg);
}
public function e(string $msg) {
$this->logMsg(LOG_ERR, $msg);
}
public function w(string $msg) {
$this->logMsg(LOG_WARN, $msg);
}
public function n(string $msg) {
$this->logMsg(LOG_NOTICE, $msg);
}
public function i(string $msg) {
$this->logMsg(LOG_INFO, $msg);
}
public function d(string $msg) {
$this->logMsg(LOG_DEBUG, $msg);
}
public function setLogLevel(int $level) {
/**
* Funktion zum Setzen des Loglevels. Mögliche Werte sind
* LOG_EMERG(0), LOG_ALERT(1), LOG_CRIT(2), LOG_ERR(3),
* LOG_WARNING(4), LOG_NOTICE(5), LOG_INFO(6) oder LOG_DEBUG(7).
* Es wird geprüft, ob das übergebene Level gültig ist.
*/
if (in_array($level, array(0, 1, 2, 3, 4, 5, 6, 7)) === true) {
$this->loglevel = $level;
$this->d("Loglevel set to {$this->loglevel}");
} else {
echo "{$level} is not a valid loglevel.";
}
}
private function addLevel(int $level, string $msg): string {
/**
* Stellt der Meldung das Loglevel voran.
*/
$text = "[$level] ".$msg;
return $text;
}
private function logMsg(string $msglevel, string $msg) {
/**
* Übergibt die Meldung an die Funktion syslog. Vorher wird
* entschieden, ob eine Meldung ausgegeben wird oder nicht. Dazu
* wird geschaut, ob das Messagelevel kleiner oder gleich dem
* Loglevel ist..
*/
$msg = $this->addLevel($msglevel, $msg);
if ($msglevel <= $this->loglevel) {
syslog($msglevel, $msg);
}
}
}
?>