errors_reporting.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. airbrake.Close()
  54. }
  55. func reportError(err error, req *http.Request) {
  56. if bugsnagEnabled {
  57. bugsnag.Notify(err, req)
  58. }
  59. if honeybadgerEnabled {
  60. headers := make(honeybadger.CGIData)
  61. for k, v := range req.Header {
  62. key := "HTTP_" + headersReplacer.Replace(strings.ToUpper(k))
  63. headers[key] = v[0]
  64. }
  65. honeybadger.Notify(err, req.URL, headers)
  66. }
  67. if sentryEnabled {
  68. hub := sentry.CurrentHub().Clone()
  69. hub.Scope().SetRequest(req)
  70. hub.Scope().SetLevel(sentry.LevelError)
  71. eventID := hub.CaptureException(err)
  72. if eventID != nil {
  73. hub.Flush(sentryTimeout)
  74. }
  75. }
  76. if airbrakeEnabled {
  77. airbrake.Notify(err, req)
  78. }
  79. }