-
Notifications
You must be signed in to change notification settings - Fork 1
/
slog.v
116 lines (102 loc) · 1.78 KB
/
slog.v
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
module slog
import term
const (
empty_str = ''
)
pub const (
__logger = &Logger(voidptr(0))
max_level = Level.disabled
default_env = 'V_LOG'
)
pub enum Level {
disabled
error
warn
info
debug
trace
}
fn level___from_str(lv_str string) Level {
match lv_str {
'error' {
return .error
}
'warn' {
return .warn
}
'info' {
return .info
}
'debug' {
return .debug
}
'trace' {
return .trace
}
else {
$if !prod {
dump('invalid level: $lv_str')
panic('Invalid level result in `.disabled` in production (-prod)')
}
return .disabled
}
}
}
pub fn set_max_level(level Level) {
unsafe {
max_level = level
}
$if dbg_logger ? {
dump(max_level)
}
}
[inline]
pub fn get_logger() &Logger {
$if !prod {
if isnil(__logger) {
panic('logger is nil in production (-prod)')
}
}
return __logger
}
[inline]
pub fn set_logger(log &Logger) {
mut log_mut := unsafe { &__logger }
unsafe {
*log_mut = log
}
}
pub fn log(lv Level, target string, msg string) {
if max_level == .disabled {
return
}
logger_ := get_logger()
// if logger_.enabled(target, lv) { // FIXME: This result in segfault...
logger_.log(lv, target, msg)
// }
}
pub interface Logger {
log(lv Level, target string, msg string)
// enabled(target string, lv Level) bool
}
pub struct BaseLogger {}
pub fn (lg &BaseLogger) fmt_level_for_term(lv Level) string {
return match lv {
.disabled { empty_str }
.error { term.red('ERROR') }
.warn { term.yellow('WARN ') }
.info { term.green('INFO ') }
.debug { term.cyan('DEBUG') }
.trace { term.magenta('TRACE') }
}
}
pub fn (lg &BaseLogger) fmt_level(lv Level) string {
return match lv {
.disabled { empty_str }
.error { 'ERROR' }
.warn { 'WARN' }
.info { 'INFO' }
.debug { 'DEBUG' }
.trace { 'TRACE' }
}
}