-
Notifications
You must be signed in to change notification settings - Fork 1
/
klog.go
110 lines (89 loc) · 2.07 KB
/
klog.go
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
package goklog
import (
"fmt"
"github.com/go-errors/errors"
"os"
"strconv"
"sync"
"time"
)
type ListenerFunc func(string)
func emptyListener(message string) {
}
type KLog struct {
listener ListenerFunc
inspectOpened bool
formatter string
printLevel int
}
var instance *KLog
var once sync.Once
const (
NORMAL_LEVEL = iota
ERROR_LEVEL
VITAL
)
// copied from: https://stackoverflow.com/questions/40326540/how-to-assign-default-value-if-env-var-is-empty
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func getErrorCallStack(e error) string {
if e == nil {
return ""
}
e0, ok := e.(*errors.Error)
if !ok {
return e.Error()
}
callStack := string(e0.ErrorStack())
return callStack
}
func GetInstance() *KLog {
once.Do(func() {
level, err := strconv.ParseInt(getenv("KLOG_PRINT_LEVEL", "0"), 0, 8)
if err != nil {
fmt.Println("System environment KLOG_PRINT_LEVEL is polluted")
level = NORMAL_LEVEL
}
instance = &KLog{
listener: emptyListener,
inspectOpened: false,
formatter: "2006-01-02-15.04.05.999",
printLevel: int(level),
}
})
return instance
}
func (klog *KLog) SetListener(listener ListenerFunc) {
klog.listener = listener
}
func (klog *KLog) ToggleInspector() {
klog.inspectOpened = !klog.inspectOpened
}
func (klog *KLog) LogIn(title string, text string) {
if klog.inspectOpened {
klog.Info(title, text, NORMAL_LEVEL)
}
}
func (klog *KLog) Info(title string, text string, level int) {
today := time.Now()
logText := fmt.Sprintf("[klog:%s] (%s) %s", today.Format(klog.formatter), title, text)
if level >= klog.printLevel {
fmt.Println(logText)
}
klog.listener(logText)
}
func (klog *KLog) LogVital(title string, text string) {
klog.Info(title, text, VITAL)
}
func (klog *KLog) LogError(title string, err error) {
errorText := getErrorCallStack(err)
klog.Info(fmt.Sprintf("error-response-%s", title), errorText, ERROR_LEVEL)
}
func (klog *KLog) LogNormal(title string, text string) {
klog.Info(title, text, NORMAL_LEVEL)
}