-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
80 lines (68 loc) · 1.92 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
package client
import (
"github.com/hopeio/cherry/utils/log"
stringsi "github.com/hopeio/cherry/utils/strings"
"go.uber.org/zap"
"time"
)
type LogLevel int8
const (
LogLevelSilent LogLevel = iota
LogLevelError
LogLevelInfo
)
type Body struct {
Data []byte
ContentType ContentType
}
func NewBody(data []byte, contentType ContentType) *Body {
return &Body{Data: data, ContentType: contentType}
}
func (b *Body) IsJson() bool {
return b.ContentType == ContentTypeJson
}
func (b *Body) IsProtobuf() bool {
return b.ContentType == ContentTypeProtobuf
}
type LogCallback func(url, method, auth string, reqBody, respBody *Body, status int, process time.Duration, err error)
type Logger interface {
SetPrefix(string)
Printf(format string, v ...interface{})
Println(v ...interface{})
}
var defaultLog = DefaultLogger
func DefaultLogger(url, method, auth string, reqBody, respBody *Body, status int, process time.Duration, err error) {
reqField, respField := zap.Skip(), zap.Skip()
if reqBody != nil {
key := "param"
if reqBody.IsJson() {
reqField = zap.Reflect(key, log.BytesJson(reqBody.Data))
} else if reqBody.IsProtobuf() {
reqField = zap.Binary(key, reqBody.Data)
} else {
reqField = zap.String(key, stringsi.BytesToString(reqBody.Data))
}
}
if respBody != nil && respBody.Data != nil {
key := "result"
if respBody.IsJson() {
respField = zap.Reflect(key, log.BytesJson(respBody.Data))
} else if respBody.IsProtobuf() {
respField = zap.Binary(key, respBody.Data)
} else {
if len(respBody.Data) > 500 {
respField = zap.String(key, "result is too long")
} else {
respField = zap.String(key, stringsi.BytesToString(respBody.Data))
}
}
}
log.Default().Logger.Info("third-request", zap.String("url", url),
zap.String("method", method),
reqField,
zap.Duration("processTime", process),
respField,
zap.String("other", auth),
zap.Int("status", status),
zap.Error(err))
}