forked from whatvn/denny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
49 lines (45 loc) · 1.05 KB
/
logger.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
package http
import (
"context"
"github.com/kenkinsai/denny"
"github.com/kenkinsai/denny/log"
"time"
)
func Logger() denny.HandleFunc {
return func(ctx *denny.Context) {
logger := log.New(&log.JSONFormatter{})
var (
clientIP = ctx.ClientIP()
method = ctx.Request.Method
userAgent = ctx.Request.UserAgent()
uri = ctx.Request.RequestURI
errs string
start = time.Now()
)
logger.WithFields(map[string]interface{}{
"ClientIP": clientIP,
"RequestMethod": method,
"UserAgent": userAgent,
"Uri": uri,
})
ctx.Request = ctx.Request.WithContext(context.WithValue(ctx, log.LogKey, logger))
ctx.Set(log.LogKey, logger)
ctx.Next()
var (
statusCode = ctx.Writer.Status()
)
logger.WithField("Status", statusCode)
if ctx.Errors != nil {
bs, err := ctx.Errors.MarshalJSON()
if err == nil {
errs = string(bs)
}
}
if len(errs) > 0 {
logger.WithField("Errors", errs)
}
end := time.Now()
logger.WithField("end", end)
logger.Infof("latency: %v", end.Sub(start))
}
}