chore: exclude static endpoints from sentry tracing

chore: include user info to sentry tracing again
This commit is contained in:
Ferdinand Mütsch 2021-04-29 21:19:43 +02:00
parent 37d4d58b57
commit 5a8287a06b
3 changed files with 43 additions and 4 deletions

View File

@ -100,6 +100,13 @@ func (l *SentryWrapperLogger) log(msg string, level sentry.Level) {
sentry.CaptureEvent(event)
}
var excludedRoutes = []string{
"GET /assets",
"GET /api/health",
"GET /swagger-ui",
"GET /docs",
}
func initSentry(config sentryConfig, debug bool) {
if err := sentry.Init(sentry.ClientOptions{
Dsn: config.Dsn,
@ -112,8 +119,10 @@ func initSentry(config sentryConfig, debug bool) {
hub := sentry.GetHubFromContext(ctx.Span.Context())
txName := hub.Scope().Transaction()
if strings.HasPrefix(txName, "GET /assets") || strings.HasPrefix(txName, "GET /api/health") {
return sentry.SampledFalse
for _, ex := range excludedRoutes {
if strings.HasPrefix(txName, ex) {
return sentry.SampledFalse
}
}
if txName == "POST /api/heartbeat" {
return sentry.UniformTracesSampler(config.SampleRateHeartbeats).Sample(ctx)

View File

@ -2,7 +2,6 @@ package main
import (
"embed"
sentryhttp "github.com/getsentry/sentry-go/http"
"io/fs"
"log"
"net/http"
@ -184,7 +183,7 @@ func main() {
router.Use(middlewares.NewLoggingMiddleware(logbuch.Info, []string{"/assets"}))
router.Use(handlers.RecoveryHandler())
if config.Sentry.Dsn != "" {
router.Use(sentryhttp.New(sentryhttp.Options{Repanic: true}).Handle)
router.Use(middlewares.NewSentryMiddleware())
}
rootRouter.Use(middlewares.NewSecurityMiddleware())

31
middlewares/sentry.go Normal file
View File

@ -0,0 +1,31 @@
package middlewares
import (
"context"
"github.com/getsentry/sentry-go"
sentryhttp "github.com/getsentry/sentry-go/http"
"net/http"
)
// SentryMiddleware is a wrapper around sentryhttp to include user information to traces
type SentryMiddleware struct {
handler http.Handler
}
func NewSentryMiddleware() func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return sentryhttp.New(sentryhttp.Options{
Repanic: true,
}).Handle(&SentryMiddleware{handler: h})
}
}
func (h *SentryMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "-", "-")
h.handler.ServeHTTP(w, r.WithContext(ctx))
if hub := sentry.GetHubFromContext(ctx); hub != nil {
if user := GetPrincipal(r); user != nil {
hub.Scope().SetUser(sentry.User{ID: user.ID})
}
}
}