-
Notifications
You must be signed in to change notification settings - Fork 0
/
newrelic.go
56 lines (41 loc) · 1.52 KB
/
newrelic.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
package middleware
import (
"net/http"
"strings"
"github.com/go-chi/chi"
newrelic "github.com/newrelic/go-agent"
"github.com/rickbassham/example-go/pkg/tracing"
)
// NewRelicChiRouter will start a newrelic transaction for the request. It will
// name the transaction to match the chi route. It will also add custom attributes
// to the transaction, such as the trace id, any url parameters, and query string
// parameters. These attributes make it easy to tie your New Relic traces to logs.
// This middleware can be used in place of using newrelic.WrapHandleFunc
// everywhere.
func NewRelicChiRouter(nr newrelic.Application) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
txn := nr.StartTransaction(r.URL.Path, w, r)
r = r.WithContext(newrelic.NewContext(r.Context(), txn))
next.ServeHTTP(txn, r)
rctx := chi.RouteContext(r.Context())
txn.AddAttribute("X-Trace-Id", tracing.FromContext(r.Context())) // nolint
for i := range rctx.URLParams.Keys {
if rctx.URLParams.Keys[i] == "*" {
continue
}
txn.AddAttribute(rctx.URLParams.Keys[i], rctx.URLParams.Values[i]) // nolint
}
for k, v := range r.URL.Query() {
txn.AddAttribute(k, v[0]) // nolint
}
routePattern := strings.Join(rctx.RoutePatterns, "")
routePattern = strings.Replace(routePattern, "/*", "", -1)
if routePattern != "" {
txn.SetName(routePattern) // nolint
}
txn.End() // nolint
}
return http.HandlerFunc(fn)
}
}