aboutsummaryrefslogtreecommitdiff
path: root/app/class/Logger.php
blob: e2ab4b6d99a627245a3e186b1cf20522284c7729 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php

namespace Wcms;

use RuntimeException;
use Throwable;

/**
 * Class used to log messages.
 * It must be init once at the very beginning of the application.
 */
class Logger
{
    private static $file = false;
    private static $verbosity = 4;

    /**
     * Initialize the logger by openning the file and setting the log level.
     *
     * @param string $path the logfile's path
     * @param int $verbosity 0: no log, 1: errors only, 2: add warn, 3: add info, 4: add debug.
     * @throws RuntimeException if failed to create logfile.
     */
    public static function init(string $path, int $verbosity = 4): void
    {
        if (!is_dir(dirname($path))) {
            throw new RuntimeException("Parent directory of '$path' does not exist.");
        }
        if (!is_writable(dirname($path))) {
            throw new RuntimeException("Parent directory of '$path' is not writable.");
        }
        if (is_file($path) && !is_writable($path)) {
            throw new RuntimeException("The logfile '$path' is not writable.");
        }
        self::$file = fopen($path, "a");
        if (self::$file === false) {
        }
        self::$verbosity = $verbosity;
    }

    protected static function write(string $level, string $msg, array $args = [])
    {
        $caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1];
        $pwd = getcwd() . DIRECTORY_SEPARATOR;
        $args = array_merge([
            "[ $level ]",
            str_replace($pwd, '', $caller['file']),
            $caller['line']
        ], $args);
        vfprintf(self::$file, date('c') . " %-9s %s(%d) $msg\n", $args);
    }

    protected static function exceptionmessage(Throwable $e): string
    {
        return "{$e->getMessage()} in {$e->getFile()}({$e->getLine()})";
    }

    /**
     * Log an error message using printf format.
     */
    public static function error(string $msg, ...$args)
    {
        if (self::$verbosity > 0) {
            self::write('ERROR', $msg, $args);
        }
    }

    /**
     * Log a warning message using printf format.
     */
    public static function warning(string $msg, ...$args)
    {
        if (self::$verbosity > 1) {
            self::write('WARN', $msg, $args);
        }
    }

    /**
     * Log an info message using printf format.
     */
    public static function info(string $msg, ...$args)
    {
        if (self::$verbosity > 2) {
            self::write('INFO', $msg, $args);
        }
    }

    /**
     * Log a debug message using printf format.
     */
    public static function debug(string $msg, ...$args)
    {
        if (self::$verbosity > 3) {
            self::write('DEBUG', $msg, $args);
        }
    }

    /**
     * Log an exception as an error.
     */
    public static function errorex(Throwable $e, bool $withtrace = false)
    {
        if (self::$verbosity > 0) {
            $msg = self::exceptionmessage($e);
            if ($withtrace) {
                // TODO: Maybe print a more beautiful stack trace.
                $msg .= PHP_EOL . $e->getTraceAsString();
            }
            self::write('ERROR', $msg);
        }
    }

    /**
     * Log an exception as a warning.
     */
    public static function warningex(Throwable $e)
    {
        if (self::$verbosity > 1) {
            self::write('WARN', self::exceptionmessage($e));
        }
    }

    /**
     * Log an exception as an info.
     */
    public static function infoex(Throwable $e)
    {
        if (self::$verbosity > 2) {
            self::write('INFO', self::exceptionmessage($e));
        }
    }

    /**
     * Log an exception as a debug.
     */
    public static function debugex(Throwable $e)
    {
        if (self::$verbosity > 3) {
            self::write('DEBUG', self::exceptionmessage($e));
        }
    }
}