forked from go-kratos/kratos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
118 lines (106 loc) · 2.41 KB
/
handler.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
117
118
package log
import (
"context"
"time"
pkgerr "github.com/pkg/errors"
)
const (
_timeFormat = "2006-01-02T15:04:05.999999"
// log level defined in level.go.
_levelValue = "level_value"
// log level name: INFO, WARN...
_level = "level"
// log time.
_time = "time"
// request path.
// _title = "title"
// log file.
_source = "source"
// common log filed.
_log = "log"
// app name.
_appID = "app_id"
// container ID.
_instanceID = "instance_id"
// uniq ID from trace.
_tid = "traceid"
// request time.
// _ts = "ts"
// requester.
_caller = "caller"
// container environment: prod, pre, uat, fat.
_deplyEnv = "env"
// container area.
_zone = "zone"
// mirror flag
_mirror = "mirror"
// color.
_color = "color"
// env_color
_envColor = "env_color"
// cluster.
_cluster = "cluster"
)
// Handler is used to handle log events, outputting them to
// stdio or sending them to remote services. See the "handlers"
// directory for implementations.
//
// It is left up to Handlers to implement thread-safety.
type Handler interface {
// Log handle log
// variadic D is k-v struct represent log content
Log(context.Context, Level, ...D)
// SetFormat set render format on log output
// see StdoutHandler.SetFormat for detail
SetFormat(string)
// Close handler
Close() error
}
func newHandlers(filters []string, handlers ...Handler) *Handlers {
set := make(map[string]struct{})
for _, k := range filters {
set[k] = struct{}{}
}
return &Handlers{filters: set, handlers: handlers}
}
// Handlers a bundle for hander with filter function.
type Handlers struct {
filters map[string]struct{}
handlers []Handler
}
// Log handlers logging.
func (hs Handlers) Log(ctx context.Context, lv Level, d ...D) {
hasSource := false
for i := range d {
if _, ok := hs.filters[d[i].Key]; ok {
d[i].Value = "***"
}
if d[i].Key == _source {
hasSource = true
}
}
if !hasSource {
fn := funcName(3)
errIncr(lv, fn)
d = append(d, KVString(_source, fn))
}
d = append(d, KV(_time, time.Now()), KVInt64(_levelValue, int64(lv)), KVString(_level, lv.String()))
for _, h := range hs.handlers {
h.Log(ctx, lv, d...)
}
}
// Close close resource.
func (hs Handlers) Close() (err error) {
for _, h := range hs.handlers {
if e := h.Close(); e != nil {
err = pkgerr.WithStack(e)
}
}
return
}
// SetFormat .
func (hs Handlers) SetFormat(format string) {
for _, h := range hs.handlers {
h.SetFormat(format)
}
}