-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmiddleware.go
80 lines (70 loc) · 1.92 KB
/
middleware.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 chilogger
import (
"fmt"
"net/http"
"time"
"go.uber.org/zap/zapcore"
"github.com/sirupsen/logrus"
"github.com/go-chi/chi/middleware"
"go.uber.org/zap"
)
type chilogger struct {
logZ *zap.Logger
logL *logrus.Logger
name string
}
// NewLogrusMiddleware returns a new Logrus Middleware handler.
func NewLogrusMiddleware(name string, logger *logrus.Logger) func(next http.Handler) http.Handler {
return chilogger{
logL: logger,
name: name,
}.middleware
}
// NewZapMiddleware returns a new Zap Middleware handler.
func NewZapMiddleware(name string, logger *zap.Logger) func(next http.Handler) http.Handler {
return chilogger{
logZ: logger,
name: name,
}.middleware
}
func (c chilogger) middleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
var requestID string
if reqID := r.Context().Value(middleware.RequestIDKey); reqID != nil {
requestID = reqID.(string)
}
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
latency := time.Since(start)
if c.logZ != nil {
fields := []zapcore.Field{
zap.Int("status", ww.Status()),
zap.Duration("took", latency),
zap.Int64(fmt.Sprintf("measure#%s.latency", c.name), latency.Nanoseconds()),
zap.String("remote", r.RemoteAddr),
zap.String("request", r.RequestURI),
zap.String("method", r.Method),
}
if requestID != "" {
fields = append(fields, zap.String("request-id", requestID))
}
c.logZ.Info("request completed", fields...)
}
if c.logL != nil {
fields := logrus.Fields{
"status": ww.Status(),
"took": latency,
fmt.Sprintf("measure#%s.latency", c.name): latency.Nanoseconds(),
"remote": r.RemoteAddr,
"request": r.RequestURI,
"method": r.Method,
}
if requestID != "" {
fields["request-id"] = requestID
}
c.logL.WithFields(fields).Info("request completed")
}
}
return http.HandlerFunc(fn)
}