-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxaccess_pre17.go
83 lines (71 loc) · 2.21 KB
/
xaccess_pre17.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
// +build !go1.7
// Package xaccess is a middleware that logs all access requests performed on the sub handler
// using github.com/rs/xlog and github.com/rs/xstats stored in context.
package xaccess
import (
"net/http"
"strconv"
"time"
"github.com/rs/xhandler"
"github.com/rs/xlog"
"github.com/rs/xstats"
"github.com/zenazn/goji/web/mutil"
"golang.org/x/net/context"
)
// NewHandler returns a handler that log access information about each request performed
// on the provided sub-handlers. Uses context's github.com/rs/xlog and
// github.com/rs/xstats if present for logging.
func NewHandler() func(next xhandler.HandlerC) xhandler.HandlerC {
return func(next xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// Time request
reqStart := time.Now()
// Sniff the status and content size for logging
lw := mutil.WrapWriter(w)
// Call the next handler
next.ServeHTTPC(ctx, lw, r)
// Conpute request duration
reqDur := time.Since(reqStart)
// Get request status
status := responseStatus(ctx, lw.Status())
// Log request stats
sts := xstats.FromContext(ctx)
tags := []string{
"status:" + status,
"status_code:" + strconv.Itoa(lw.Status()),
}
sts.Timing("request_time", reqDur, tags...)
sts.Histogram("request_size", float64(lw.BytesWritten()), tags...)
// Log access info
log := xlog.FromContext(ctx)
log.Infof("%s %s %03d", r.Method, ellipsize(r.URL.String(), 100), lw.Status(), xlog.F{
"type": "access",
"status": status,
"status_code": lw.Status(),
"duration": reqDur.Seconds(),
"size": lw.BytesWritten(),
})
})
}
}
func responseStatus(ctx context.Context, statusCode int) string {
if ctx.Err() != nil {
if ctx.Err() == context.DeadlineExceeded {
return "timeout"
}
return "canceled"
} else if statusCode >= 200 && statusCode < 300 {
return "ok"
}
return "error"
}
// ellipsize shorten a string using ellises in the middle if the string
// is longer than max.
func ellipsize(s string, max int) string {
if max <= 3 {
s = "..."[:max]
} else if l := len(s); l > max {
s = s[:max/2-1] + "..." + s[l-(max/2)+1:]
}
return s
}