/
log.go
149 lines (131 loc) · 4.08 KB
/
log.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package log
import (
"context"
"fmt"
"github.com/holgerfy/go-pkg/funcs"
"github.com/holgerfy/go-pkg/unique"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"io"
"os"
"runtime"
"strconv"
"time"
)
type Log struct {
logger *zap.Logger
}
const loggerKey = iota
var log = &Log{}
func Start() {
level := zap.DebugLevel
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
encoderConfig.MessageKey = "msg"
encoderConfig.TimeKey = "ts"
encoderConfig.LevelKey = "level"
encoder := zapcore.NewConsoleEncoder(encoderConfig)
core := zapcore.NewCore(
encoder,
zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(getWriter())),
level,
)
log.logger = zap.New(core, zap.AddStacktrace(zap.ErrorLevel))
}
func getWriter() io.Writer {
logDir := funcs.GetRoot()
logWriter, _ := rotatelogs.New(logDir+"/%Y%m%d.log",
rotatelogs.WithMaxAge(time.Hour*24*7),
rotatelogs.WithRotationTime(time.Hour*24),
)
return logWriter
}
func Logger() *Log {
return log
}
func WithFields(ctx context.Context, fields map[string]string) context.Context {
fieldArr := make([]zap.Field, 0)
for k, v := range fields {
f := zap.String(k, v)
fieldArr = append(fieldArr, f)
}
l := WithCtx(ctx)
return context.WithValue(ctx, loggerKey, l.With(fieldArr...))
}
func NewContext(ctx context.Context, fields ...zapcore.Field) context.Context {
return context.WithValue(ctx, loggerKey, WithCtx(ctx).With(fields...))
}
func WithCtx(ctx context.Context) *zap.Logger {
if ctx == nil {
return log.logger
}
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
return ctxLogger
}
return log.logger
}
func (l *Log) Info(ctx context.Context, args ...interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
WithCtx(ctx).Info(fmt.Sprint(args), zap.String("file", file), zap.String("line", string(line)), zap.String("func", f.Name()))
}
func (l *Log) Error(ctx context.Context, args ...interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
WithCtx(ctx).Error(fmt.Sprint(args), zap.String("file", file), zap.String("line", string(line)), zap.String("func", f.Name()))
}
func (l *Log) Debug(ctx context.Context, args ...interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
WithCtx(ctx).Debug(fmt.Sprint(args), zap.String("file", file), zap.String("line", string(line)), zap.String("func", f.Name()))
}
func (l *Log) Warn(ctx context.Context, args ...interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
WithCtx(ctx).Warn(fmt.Sprint(args), zap.String("file", file), zap.String("line", string(line)), zap.String("func", f.Name()))
}
func (l *Log) Fatal(ctx context.Context, args ...interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
WithCtx(ctx).Fatal(fmt.Sprint(args), zap.String("file", file), zap.String("line", string(line)), zap.String("func", f.Name()))
}
func GrpcUnaryServerInterceptor(l *Log) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
startTime := time.Now()
reqId := ""
headers, ok := metadata.FromIncomingContext(ctx)
if ok {
reqIdArr := headers.Get("Req-Id")
if len(reqIdArr) > 0 {
reqId = reqIdArr[0]
}
}
if reqId == "" {
reqId = unique.Uuid()
}
items := map[string]string{
"method": info.FullMethod,
"req-id": reqId,
}
newCtx := WithFields(ctx, items)
resp, err = handler(newCtx, req)
code := status.Code(err)
duration := time.Since(startTime)
items1 := map[string]string{
"code": strconv.Itoa(int(code)),
"duration": duration.String(),
}
fields := make([]zap.Field, 0)
for k, v := range items1 {
f := zap.String(k, v)
fields = append(fields, f)
}
WithCtx(newCtx).Info("serverLogger", fields...)
return resp, err
}
}