-
Notifications
You must be signed in to change notification settings - Fork 0
/
honeycomb_helper.go
78 lines (65 loc) · 2.25 KB
/
honeycomb_helper.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
package config
import (
"context"
"log"
"net/http"
"time"
libhoney "github.com/honeycombio/libhoney-go"
)
var (
hostname string
hnyDatasetName = "undead.questions"
hnyContextKey = "enigmaEvent"
)
type HoneyResponseWriter struct {
*libhoney.Event
http.ResponseWriter
StatusCode int
}
func (hrw *HoneyResponseWriter) WriteHeader(status int) {
// Mark this down for adding to the libhoney event later.
hrw.StatusCode = status
hrw.ResponseWriter.WriteHeader(status)
}
func addRequestProps(req *http.Request, ev *libhoney.Event) {
// Add a variety of details about the HTTP request, such as user agent
// and method, to any created libhoney event.
ev.AddField("request.method", req.Method)
ev.AddField("request.path", req.URL.Path)
ev.AddField("request.host", req.URL.Host)
ev.AddField("request.proto", req.Proto)
ev.AddField("request.content_length", req.ContentLength)
ev.AddField("request.remote_addr", req.RemoteAddr)
ev.AddField("request.user_agent", req.UserAgent())
}
// HoneycombMiddleware will wrap our HTTP handle funcs to automatically
// generate an event-per-request and set properties on them.
func HoneycombMiddleware(fn func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// We'll time each HTTP request and add that as a property to
// the sent Honeycomb event, so start the timer for that.
startHandler := time.Now()
ev := libhoney.NewEvent()
defer func() {
if err := ev.Send(); err != nil {
log.Print("Error sending libhoney event: ", err)
}
}()
addRequestProps(r, ev)
// Create a context where we will store the libhoney event. We
// will add default values to this event for every HTTP
// request, and the user can access it to add their own
// (powerful, custom) fields.
ctx := context.WithValue(r.Context(), hnyContextKey, ev)
reqWithContext := r.WithContext(ctx)
honeyResponseWriter := &HoneyResponseWriter{
Event: ev,
ResponseWriter: w,
StatusCode: 200,
}
fn(honeyResponseWriter, reqWithContext)
ev.AddField("response.status_code", honeyResponseWriter.StatusCode)
handlerDuration := time.Since(startHandler)
ev.AddField("timers.total_time_ms", handlerDuration/time.Millisecond)
}
}