errors_reporting.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "net/http"
  4. "strings"
  5. "time"
  6. "github.com/airbrake/gobrake/v5"
  7. "github.com/bugsnag/bugsnag-go/v2"
  8. "github.com/getsentry/sentry-go"
  9. "github.com/honeybadger-io/honeybadger-go"
  10. )
  11. var (
  12. bugsnagEnabled bool
  13. honeybadgerEnabled bool
  14. sentryEnabled bool
  15. airbrakeEnabled bool
  16. airbrake *gobrake.Notifier
  17. headersReplacer = strings.NewReplacer("-", "_")
  18. sentryTimeout = 5 * time.Second
  19. )
  20. func initErrorsReporting() {
  21. if len(conf.BugsnagKey) > 0 {
  22. bugsnag.Configure(bugsnag.Configuration{
  23. APIKey: conf.BugsnagKey,
  24. ReleaseStage: conf.BugsnagStage,
  25. })
  26. bugsnagEnabled = true
  27. }
  28. if len(conf.HoneybadgerKey) > 0 {
  29. honeybadger.Configure(honeybadger.Configuration{
  30. APIKey: conf.HoneybadgerKey,
  31. Env: conf.HoneybadgerEnv,
  32. })
  33. honeybadgerEnabled = true
  34. }
  35. if len(conf.SentryDSN) > 0 {
  36. sentry.Init(sentry.ClientOptions{
  37. Dsn: conf.SentryDSN,
  38. Release: conf.SentryRelease,
  39. Environment: conf.SentryEnvironment,
  40. })
  41. sentryEnabled = true
  42. }
  43. if len(conf.AirbrakeProjecKey) > 0 {
  44. airbrake = gobrake.NewNotifierWithOptions(&gobrake.NotifierOptions{
  45. ProjectId: int64(conf.AirbrakeProjecID),
  46. ProjectKey: conf.AirbrakeProjecKey,
  47. Environment: conf.AirbrakeEnv,
  48. })
  49. airbrakeEnabled = true
  50. }
  51. }
  52. func closeErrorsReporting() {
  53. if airbrake != nil {
  54. airbrake.Close()
  55. }
  56. }
  57. func reportError(err error, req *http.Request) {
  58. if bugsnagEnabled {
  59. bugsnag.Notify(err, req)
  60. }
  61. if honeybadgerEnabled {
  62. headers := make(honeybadger.CGIData)
  63. for k, v := range req.Header {
  64. key := "HTTP_" + headersReplacer.Replace(strings.ToUpper(k))
  65. headers[key] = v[0]
  66. }
  67. honeybadger.Notify(err, req.URL, headers)
  68. }
  69. if sentryEnabled {
  70. hub := sentry.CurrentHub().Clone()
  71. hub.Scope().SetRequest(req)
  72. hub.Scope().SetLevel(sentry.LevelError)
  73. eventID := hub.CaptureException(err)
  74. if eventID != nil {
  75. hub.Flush(sentryTimeout)
  76. }
  77. }
  78. if airbrakeEnabled {
  79. airbrake.Notify(err, req)
  80. }
  81. }