-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathglobal_fields.go
63 lines (54 loc) · 1.72 KB
/
global_fields.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
package logbus
import (
"os"
"github.com/rs/xid"
"github.com/sandwich-go/boost/xip"
"github.com/sandwich-go/boost/xtime"
"go.uber.org/zap"
)
var globalFields []zap.Field
var cacheUserDefineFields []zap.Field
func init() {
for _, key := range []string{"sys_env_name", "sys_stage", "sys_cd_service"} {
val := os.Getenv(key)
if val != "" {
ReservedGlobalFields = append(ReservedGlobalFields, String(key, val))
}
}
ReservedGlobalFields = append(ReservedGlobalFields, String("server_id", xid.New().String()))
ReservedGlobalFields = append(ReservedGlobalFields, String("server_ip", xip.GetLocalIP()))
ReservedGlobalFields = append(ReservedGlobalFields, Int64("server_birth", xtime.Unix()))
if hostName, err := os.Hostname(); err == nil {
ReservedGlobalFields = append(ReservedGlobalFields, String("host_name", hostName))
} else {
ReservedGlobalFields = append(ReservedGlobalFields, String("host_name", "-"))
}
AppendGlobalFields()
}
// ReservedGlobalFields 预留的全局字段,可以通过显式这只为空清除
var ReservedGlobalFields []Field
func GetGlobalFields() []Field { return globalFields }
func SetGlobalFields(fields []Field) {
cacheUserDefineFields = fields
freshGlobal()
}
func AppendGlobalFields(fields ...Field) {
cacheUserDefineFields = append(cacheUserDefineFields, fields...)
freshGlobal()
}
func freshGlobal() {
globalFields = nil
for _, v := range ReservedGlobalFields {
overrideByUser := false
for _, vt := range cacheUserDefineFields {
if v.Key == vt.Key {
overrideByUser = true
}
}
if !overrideByUser {
// 用户层没有覆盖的字段则使用默认字段
globalFields = append(globalFields, v)
}
}
globalFields = append(globalFields, cacheUserDefineFields...)
}