-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logger.php
92 lines (56 loc) · 1.7 KB
/
Logger.php
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
<?php
class Logger {
const
LOG_NONE = 0,
LOG_BASIC = 1,
LOG_VERBOSE = 2,
LOG_DEBUG = 3;
public
$message = ['name' => '', 'version' => ''],
$statusCode = 0;
protected
$file,
$level = self::LOG_BASIC;
function __construct (string $file) {
$this->file = $file;
}
function setLogLevel ($level = self::LOG_BASIC) {
if (!is_int ($level)) {
$levels = [
'none' => self::LOG_NONE,
'basic' => self::LOG_BASIC,
'verbose' => self::LOG_VERBOSE,
'debug' => self::LOG_DEBUG,
];
if (isset ($levels[$level]))
$level = $levels[$level];
else
$level = self::LOG_BASIC;
}
$this->logLevel = $level;
}
function setName ($name, $version) {
$this->message['name'] = $name;
$this->message['version'] = $version;
}
protected function write ($message, $level = self::LOG_BASIC) {
if ($this->level > self::LOG_NONE and $level <= $this->level) {
$prefix = date ('c').' ';
$message = str_replace ('\n', str_pad ('\n', strlen ($prefix) + 1), $message);
$dir = dirname ($this->file);
if (!is_dir ($dir)) mkdir ($dir);
file_put_contents ($this->file, $prefix.$message."\n", FILE_APPEND);
}
}
function message ($message, $level = self::LOG_BASIC) {
if ($this->level > self::LOG_NONE and $level <= $this->level) {
$this->write ($message, $level);
$this->message['messages'][] = $message;
}
}
function error ($message, $code = 403) {
$this->message['errors'][] = ['text' => $message, 'code' => $code];
$this->write ($message);
http_response_code ($code);
}
}