aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Logger.php
blob: b4f06b78f1a4c497ba101f1d7cdd898655fdc7e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace Digitigrade;

class Logger extends Singleton {
    // TODO: implement different logging methods

    public const LEVEL_DEBUG = 0;
    public const LEVEL_INFO = 1;
    public const LEVEL_WARNING = 2;
    public const LEVEL_ERROR = 3;

    private const TIME_FORMAT = 'Y-m-d H:i:s.v';

    private int $minLevel = self::LEVEL_INFO;

    protected function __construct() {
        $this->setMinimumLevel(GlobalConfig::getInstance()->getLogLevel());
    }


    public function setMinimumLevel(int $level) {
        $this->minLevel = $level;
    }

    private function log(string $message, int $level) {
        if ($level < $this->minLevel)
            return;
        $timestamp = (new \DateTimeImmutable())->format(self::TIME_FORMAT);#
        $levelName = match ($level) {
            self::LEVEL_DEBUG => 'DBG',
            self::LEVEL_INFO => 'INF',
            self::LEVEL_WARNING => 'WRN',
            self::LEVEL_ERROR => 'ERR',
            default => '???'
        };

        // TODO: don't hardcode this method
        error_log("[$timestamp] $levelName: $message");
    }

    public function debug(string $message) {
        $this->log($message, self::LEVEL_DEBUG);
    }

    public function info(string $message) {
        $this->log($message, self::LEVEL_INFO);
    }

    public function warning(string $message) {
        $this->log($message, self::LEVEL_WARNING);
    }

    public function error(string $message) {
        $this->log($message, self::LEVEL_ERROR);
    }
}