forked from improbable-eng/go-httpwares
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tripperware.go
55 lines (49 loc) · 1.74 KB
/
tripperware.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
// Copyright 2017 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package http_logrus
import (
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/mwitkow/go-httpwares"
"github.com/mwitkow/go-httpwares/tags"
)
// Tripperware is a server-side http ware for logging using logrus.
//
// This tripperware *does not* propagate a context-based logger, but act as a logger of requests.
// This includes logging of errors.
func Tripperware(entry *logrus.Entry, opts ...Option) httpwares.Tripperware {
return func(next http.RoundTripper) http.RoundTripper {
o := evaluateTripperwareOpts(opts)
return httpwares.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
startTime := time.Now()
fields := newClientRequestFields(req)
resp, err := next.RoundTrip(req)
if err != nil {
logError(o.levelForConnectivityError, entry.WithFields(fields), err)
return resp, err
}
fields["http.time_ms"] = timeDiffToMilliseconds(startTime)
fields["http.proto_major"] = resp.ProtoMajor
fields["http.response.length_bytes"] = resp.ContentLength
fields["http.status"] = resp.StatusCode
levelLogf(entry.WithFields(fields), o.levelFunc(resp.StatusCode), "request completed")
return resp, nil
})
}
}
func logError(level logrus.Level, e *logrus.Entry, err error) {
levelLogf(e.WithError(err), level, "request failed to execute, see err")
}
func newClientRequestFields(req *http.Request) logrus.Fields {
fields := logrus.Fields{
"system": SystemField,
"span.kind": "client",
"http.url.path": req.URL.Path,
"http.request.length_bytes": req.ContentLength,
}
for k, v := range http_ctxtags.ExtractOutbound(req).Values() {
fields[k] = v
}
return fields
}