This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
/
logger.go
110 lines (92 loc) · 2.58 KB
/
logger.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 logger
import (
"context"
"fmt"
"os"
"strconv"
"github.com/gin-gonic/gin"
)
// Debugf 写入调试日志
func Debugf(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Debugf(format, args...)
}
// Infof 写入消息日志
func Infof(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Infof(format, args...)
}
// Printf 写入消息日志
func Printf(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Printf(format, args...)
}
// Warnf 写入警告日志
func Warnf(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Warnf(format, args...)
}
// Errorf 写入错误日志
func Errorf(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Errorf(format, args...)
}
// Fatalf 写入重大错误日志
func Fatalf(ctx context.Context, format string, args ...interface{}) {
StartTrace(ctx).Fatalf(format, args...)
}
// ErrorStack 输出错误栈
func ErrorStack(ctx context.Context, err error) {
StartTrace(ctx).WithField(StackKey, fmt.Sprintf("%+v", err)).Errorf(err.Error())
}
//=================================================================分割线
//=================================================================分割线
//=================================================================分割线
// 定义键名
const (
TraceIDKey = "trace_id"
UserIDKey = "user_id"
RoleIDKey = "role_id"
VersionKey = "version"
HostnameKey = "hostname"
StackKey = "stack"
LogVerKey = "@version"
NamespaceKey = "@namespace"
)
var (
version string
pid = os.Getpid()
hostname, _ = os.Hostname()
)
// SetVersion 设定版本
func SetVersion(v string) {
version = v
}
// FromTraceIDContext 从上下文中获取跟踪ID
func FromTraceIDContext(ctx context.Context) string {
if v, ok := ctx.(*gin.Context); ok {
return GetTraceID(v)
}
return "main-" + strconv.Itoa(pid) // 系统上下文
}
// FromUserIDContext 从上下文中获取用户ID
func FromUserIDContext(ctx context.Context) (UserInfo, bool) {
if v, ok := ctx.(*gin.Context); ok {
return GetUserInfo(v)
}
return nil, false
}
// StartTrace 开始一个追踪单元
func StartTrace(ctx context.Context) *Entry {
if ctx == nil {
ctx = context.Background()
}
fields := map[string]interface{}{
LogVerKey: logversion,
NamespaceKey: namespace,
HostnameKey: hostname,
VersionKey: version,
}
if v := FromTraceIDContext(ctx); v != "" {
fields[TraceIDKey] = v
}
if v, ok := FromUserIDContext(ctx); ok {
fields[UserIDKey] = v.GetUserID()
}
return newEntryWithFields(fields)
}