-
Notifications
You must be signed in to change notification settings - Fork 4
/
zap.go
111 lines (94 loc) · 2.4 KB
/
zap.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
/*
* Copyright (c) Fabio da Silva Ribeiro <[email protected]>
* SPDX-License-Identifier: MIT
*/
package middleware
import (
"github.com/labstack/echo/v4"
mw "github.com/labstack/echo/v4/middleware"
"go.uber.org/zap"
)
// ZapLogConfig defines the config for Uber ZapLog middleware.
type ZapLogConfig struct {
// FieldMap set a list of fields with tags
//
// Tags to constructed the logger fields.
//
// - @id (Request ID)
// - @remote_ip
// - @uri
// - @host
// - @method
// - @path
// - @route
// - @protocol
// - @referer
// - @user_agent
// - @status
// - @error
// - @latency (In nanoseconds)
// - @latency_human (Human readable)
// - @bytes_in (Bytes received)
// - @bytes_out (Bytes sent)
// - @header:<NAME>
// - @query:<NAME>
// - @form:<NAME>
// - @cookie:<NAME>
FieldMap map[string]string
// Logger it is a zap logger
Logger *zap.Logger
// Skipper defines a function to skip middleware.
Skipper mw.Skipper
}
// DefaultZapLogConfig is the default Uber ZapLog middleware config.
var DefaultZapLogConfig = ZapLogConfig{
FieldMap: defaultFields,
Logger: func() *zap.Logger {
lg, _ := zap.NewProduction()
return lg
}(),
Skipper: mw.DefaultSkipper,
}
// ZapLog returns a middleware that logs HTTP requests.
func ZapLog() echo.MiddlewareFunc {
return ZapLogWithConfig(DefaultZapLogConfig)
}
// ZapLogWithConfig returns a Uber ZapLog middleware with config.
// See: `ZapLog()`.
func ZapLogWithConfig(cfg ZapLogConfig) echo.MiddlewareFunc {
// Defaults
if cfg.Skipper == nil {
cfg.Skipper = DefaultZapLogConfig.Skipper
}
if cfg.Logger == nil {
cfg.Logger = DefaultZapLogConfig.Logger
}
if len(cfg.FieldMap) == 0 {
cfg.FieldMap = DefaultZapLogConfig.FieldMap
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ec echo.Context) (err error) {
if cfg.Skipper(ec) {
return next(ec)
}
zFields := []zap.Field{}
logFields, err := mapFields(ec, next, cfg.FieldMap)
for k, v := range logFields {
field := zap.Any(k, v)
zFields = append(zFields, field)
}
cfg.Logger.With(zFields...).Info("handle request")
return
}
}
}
// ZapLogRecoverFn returns a ZapLog recover log function to print panic errors.
func ZapLogRecoverFn(logger *zap.Logger) mw.LogErrorFunc {
return func(_ echo.Context, err error, stack []byte) error {
logger.With(
zap.ByteString("stacktrace", stack),
zap.Error(err),
).Error("panic recover")
return err
}
}