-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.go
57 lines (50 loc) · 1.56 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
// Copyright 2020 Lauris BH. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package logger
import (
"net"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/sirupsen/logrus"
)
func Logger(category string, logger logrus.FieldLogger) func(h http.Handler) http.Handler {
return LoggerWithLevel(category, logger, logrus.InfoLevel)
}
// Logger returns a request logging middleware
func LoggerWithLevel(category string, logger logrus.FieldLogger, level logrus.Level) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
reqID := middleware.GetReqID(r.Context())
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func() {
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remoteIP = r.RemoteAddr
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
fields := logrus.Fields{
"status_code": ww.Status(),
"bytes": ww.BytesWritten(),
"duration": int64(time.Since(t1)),
"duration_display": time.Since(t1).String(),
"category": category,
"remote_ip": remoteIP,
"proto": r.Proto,
"method": r.Method,
}
if len(reqID) > 0 {
fields["request_id"] = reqID
}
logger.WithFields(fields).Logf(level, "%s://%s%s", scheme, r.Host, r.RequestURI)
}()
h.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
}