forked from bakins/logrus-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
100 lines (84 loc) · 2.29 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Package logrusmiddleware is a simple net/http middleware for logging
// using logrus
package logrusmiddleware
import (
"net/http"
"time"
"github.com/sirupsen/logrus"
)
type (
// Middleware is a middleware handler for HTTP logging
Middleware struct {
// Logger is the log.Logger instance used to log messages with the Logger middleware
Logger logrus.FieldLogger
// Name is the name of the application as recorded in latency metrics
Name string
}
// Handler is the actual middleware that handles logging
Handler struct {
http.ResponseWriter
status int
size int
m *Middleware
handler http.Handler
component string
}
)
// Handler create a new handler. component, if set, is emitted in the log messages.
func (m *Middleware) Handler(h http.Handler, component string) *Handler {
return &Handler{
m: m,
handler: h,
component: component,
}
}
// Write is a wrapper for the "real" ResponseWriter.Write
func (h *Handler) Write(b []byte) (int, error) {
if h.status == 0 {
// The status will be StatusOK if WriteHeader has not been called yet
h.status = http.StatusOK
}
size, err := h.ResponseWriter.Write(b)
h.size += size
return size, err
}
// WriteHeader is a wrapper around ResponseWriter.WriteHeader
func (h *Handler) WriteHeader(s int) {
h.ResponseWriter.WriteHeader(s)
h.status = s
}
// Header is a wrapper around ResponseWriter.Header
func (h *Handler) Header() http.Header {
return h.ResponseWriter.Header()
}
// ServeHTTP calls the "real" handler and logs using the logger
func (h *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
start := time.Now()
h.handler.ServeHTTP(rw, r)
latency := time.Since(start)
status := h.status
if status == 0 {
status = 200
}
fields := logrus.Fields{
"status": status,
"method": r.Method,
"request": r.RequestURI,
"remote": r.RemoteAddr,
"duration": float64(latency.Nanoseconds()) / float64(1000),
"size": h.size,
"referer": r.Referer(),
"user-agent": r.UserAgent(),
}
if h.m.Name != "" {
fields["name"] = h.m.Name
}
if h.component != "" {
fields["component"] = h.component
}
if l := h.m.Logger; l != nil {
l.WithFields(fields).Info("completed handling request")
} else {
logrus.WithFields(fields).Info("completed handling request")
}
}