-
Notifications
You must be signed in to change notification settings - Fork 1
/
default_logger.v
57 lines (49 loc) · 1.31 KB
/
default_logger.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
module slog
import os
import time
pub struct DefaultLogger {
BaseLogger
ModLevelMapString
ofname_prefix string
mut:
ofname string
ofile os.File
}
[params]
pub struct DefaultLoggerOpt {
pub:
level Level = Level.info
}
pub fn init_with_default_logger(ofname string, opt DefaultLoggerOpt) &DefaultLogger {
name := '$ofname-0.log'
ofile := os.open_append(name) or { panic('couldn\'t opening log file $name for appending') }
mut log := &DefaultLogger{
ofname_prefix: ofname
ofname: name
ofile: ofile
}
set_logger(log)
set_max_level(opt.level)
return log
}
pub fn (lg &DefaultLogger) log(lv Level, target string, msg string) {
if lg.enabled(target, lv) { // TODO: move inside `slog.log()` (segfault...)
lg.log_file(lv, target, msg)
lg.log_console(lv, target, msg)
}
}
fn (lg &DefaultLogger) log_file(lv Level, target string, msg string) {
mut l := unsafe { lg }
timestamp := time.now().format_ss_micro()
level := l.fmt_level(lv)
l.ofile.writeln('$timestamp [$level] $target: $msg') or {
eprintln('failed to write following msg to file: $timestamp [$level] $target: $msg')
panic(err)
}
l.ofile.flush()
}
fn (lg &DefaultLogger) log_console(lv Level, target string, msg string) {
timestamp := time.now().format_ss_micro()
level := lg.fmt_level_for_term(lv)
println('$timestamp $level $target: $msg')
}