-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogModel.go
116 lines (102 loc) · 2.42 KB
/
LogModel.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
111
112
113
114
115
116
package hyperlog
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type OutputFormat string
const (
PlainFormat OutputFormat = "PLAIN"
JSONFormat OutputFormat = "JSON"
)
type LogLevel string
const (
TraceLevel LogLevel = "trace"
DebugLevel LogLevel = "debug"
InfoLevel LogLevel = "info"
WarnLevel LogLevel = "warn"
ErrorLevel LogLevel = "error"
FatalLevel LogLevel = "fatal"
)
type LogEngine interface {
Trace(str ...interface{})
Debug(str ...interface{})
Info(str ...interface{})
Warn(str ...interface{})
Error(str ...interface{})
Fatal(str ...interface{})
Tracef(format string, args ...interface{})
Debugf(str string, args ...interface{})
Infof(str string, args ...interface{})
Warnf(str string, args ...interface{})
Errorf(str string, args ...interface{})
Fatalf(str string, args ...interface{})
WithAttributes(attr map[string]string) LogEngine
WithAttribute(key, value string) LogEngine
}
func (lvl LogLevel) Flag() int {
switch lvl {
case TraceLevel:
return 1
case DebugLevel:
return 2
case InfoLevel:
return 4
case WarnLevel:
return 8
case ErrorLevel:
return 16
case FatalLevel:
return 32
default:
return -1
}
}
func (lvl LogLevel) CanLogFor(thatLevel LogLevel) bool {
return lvl.Flag() >= thatLevel.Flag()
}
func NewLogEntryf(lvl LogLevel, attr map[string]string, format string, args ...interface{}) *LogEntry {
return &LogEntry{
Level: lvl,
Time: time.Now(),
Message: fmt.Sprintf(format, args...),
Attributes: attr,
}
}
func NewLogEntry(lvl LogLevel, attr map[string]string, message string) *LogEntry {
return &LogEntry{
Level: lvl,
Time: time.Now(),
Message: message,
Attributes: attr,
}
}
type LogEntry struct {
Level LogLevel `json:"lvl"`
Time time.Time `json:"time"`
Message string `json:"msg"`
Attributes map[string]string `json:"attrs,omitempty"`
}
func (e *LogEntry) String() string {
ret := make([]string, 0)
ret = append(ret, fmt.Sprintf("[%s]", e.Level))
ret = append(ret, e.Time.Format(time.RFC3339))
ret = append(ret, e.Message)
if e.Attributes != nil && len(e.Attributes) > 0 {
for k, v := range e.Attributes {
ret = append(ret, fmt.Sprintf("%s=%s", k, v))
}
}
return strings.Join(ret, " ")
}
func (e *LogEntry) JSONString() string {
byts, err := json.Marshal(e)
if err != nil {
return e.String()
}
return string(byts)
}
type LogShutdownHandler interface {
ShutdownLog()
}