summaryrefslogtreecommitdiff
path: root/workhorse/internal/errortracker/sentry.go
blob: 72a32c8d349fadae9894b73f86bb636030b3d88b (plain)
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
package errortracker

import (
	"fmt"
	"net/http"
	"os"
	"runtime/debug"

	"gitlab.com/gitlab-org/labkit/errortracking"

	"gitlab.com/gitlab-org/labkit/log"
)

// NewHandler allows us to handle panics in upstreams gracefully, by logging them
// using structured logging and reporting them into Sentry as `error`s with a
// proper correlation ID attached.
func NewHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if p := recover(); p != nil {
				fields := log.ContextFields(r.Context())
				log.WithFields(fields).Error(p)
				debug.PrintStack()
				// A panic isn't always an `error`, so we may have to convert it into one.
				e, ok := p.(error)
				if !ok {
					e = fmt.Errorf("%v", p)
				}
				TrackFailedRequest(r, e, fields)
			}
		}()

		next.ServeHTTP(w, r)
	})
}

func TrackFailedRequest(r *http.Request, err error, fields log.Fields) {
	captureOpts := []errortracking.CaptureOption{
		errortracking.WithContext(r.Context()),
		errortracking.WithRequest(r),
	}
	for k, v := range fields {
		captureOpts = append(captureOpts, errortracking.WithField(k, fmt.Sprintf("%v", v)))
	}

	errortracking.Capture(err, captureOpts...)
}

func Initialize(version string) error {
	// Use a custom environment variable (not SENTRY_DSN) to prevent
	// clashes with gitlab-rails.
	sentryDSN := os.Getenv("GITLAB_WORKHORSE_SENTRY_DSN")
	sentryEnvironment := os.Getenv("GITLAB_WORKHORSE_SENTRY_ENVIRONMENT")

	return errortracking.Initialize(
		errortracking.WithSentryDSN(sentryDSN),
		errortracking.WithSentryEnvironment(sentryEnvironment),
		errortracking.WithVersion(version),
	)
}