-
Notifications
You must be signed in to change notification settings - Fork 5
/
glogrus.go
80 lines (72 loc) · 1.95 KB
/
glogrus.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 glogrus
import (
"fmt"
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
)
// glogrus is a middleware handler that logs the
// request and response in a structured way
type glogrus struct {
h http.Handler
c *web.C
l *logrus.Logger
name string
}
func (glogr glogrus) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
start := time.Now()
reqID := middleware.GetReqID(*glogr.c)
glogr.l.WithFields(logrus.Fields{
"req_id": reqID,
"uri": req.RequestURI,
"method": req.Method,
"remote": req.RemoteAddr,
}).Info("req_start")
lresp := wrapWriter(resp)
glogr.h.ServeHTTP(lresp, req)
lresp.maybeWriteHeader()
latency := float64(time.Since(start)) / float64(time.Millisecond)
glogr.l.WithFields(logrus.Fields{
"req_id": reqID,
"status": lresp.status(),
"method": req.Method,
"uri": req.RequestURI,
"remote": req.RemoteAddr,
"latency": fmt.Sprintf("%6.4f ms", latency),
"app": glogr.name,
}).Info("req_served")
}
// NewGlogrus allows you to configure a goji middleware that logs all requests and responses
// using the structured logger logrus. It takes the logrus instance and the name of the app
// as the parameters and returns a middleware of type "func(c *web.C, http.Handler) http.Handler"
//
// Example:
//
// package main
//
// import(
// "github.com/zenazn/goji"
// "github.com/zenazn/goji/web/middleware"
// "github.com/goji/glogrus"
// "github.com/sirupsen/logrus"
// )
//
// func main() {
// goji.Abandon(middleware.Logger)
//
// logr := logrus.New()
// logr.Formatter = new(logrus.JSONFormatter)
// goji.Use(glogrus.NewGlogrus(logr, "my-app-name"))
//
// goji.Get("/ping", yourHandler)
// goji.Serve()
// }
//
func NewGlogrus(l *logrus.Logger, name string) func(*web.C, http.Handler) http.Handler {
fn := func(c *web.C, h http.Handler) http.Handler {
return glogrus{h: h, c: c, l: l, name: name}
}
return fn
}