sentry.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package sentry
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/getsentry/sentry-go"
  6. "github.com/imgproxy/imgproxy/v3/config"
  7. )
  8. var (
  9. enabled bool
  10. timeout = 5 * time.Second
  11. )
  12. func Init() {
  13. if len(config.SentryDSN) > 0 {
  14. sentry.Init(sentry.ClientOptions{
  15. Dsn: config.SentryDSN,
  16. Release: config.SentryRelease,
  17. Environment: config.SentryEnvironment,
  18. })
  19. enabled = true
  20. }
  21. }
  22. func Report(err error, req *http.Request, meta map[string]any) {
  23. if !enabled {
  24. return
  25. }
  26. hub := sentry.CurrentHub().Clone()
  27. hub.Scope().SetRequest(req)
  28. hub.Scope().SetLevel(sentry.LevelError)
  29. if meta != nil {
  30. hub.Scope().SetContext("Processing context", meta)
  31. }
  32. // imgproxy wraps almost all errors into *ierrors.Error, so Sentry will show
  33. // the same error type for all errors. We need to fix it.
  34. //
  35. // Instead of using hub.CaptureException(err), we need to create an event
  36. // manually and replace `*ierrors.Error` with the wrapped error type
  37. // (which is the previous exception type in the exception chain).
  38. if event := hub.Client().EventFromException(err, sentry.LevelError); event != nil {
  39. for i := 1; i < len(event.Exception); i++ {
  40. if event.Exception[i].Type == "*ierrors.Error" {
  41. event.Exception[i].Type = event.Exception[i-1].Type
  42. }
  43. }
  44. eventID := hub.CaptureEvent(event)
  45. if eventID != nil {
  46. hub.Flush(timeout)
  47. }
  48. }
  49. }