metrics.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package metrics
  2. import (
  3. "context"
  4. "net/http"
  5. "time"
  6. "github.com/imgproxy/imgproxy/v3/metrics/datadog"
  7. "github.com/imgproxy/imgproxy/v3/metrics/newrelic"
  8. "github.com/imgproxy/imgproxy/v3/metrics/prometheus"
  9. )
  10. func Init() error {
  11. prometheus.Init()
  12. if err := newrelic.Init(); err != nil {
  13. return nil
  14. }
  15. datadog.Init()
  16. return nil
  17. }
  18. func Stop() {
  19. datadog.Stop()
  20. }
  21. func Enabled() bool {
  22. return prometheus.Enabled() ||
  23. newrelic.Enabled() ||
  24. datadog.Enabled()
  25. }
  26. func StartRequest(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  27. promCancel := prometheus.StartRequest()
  28. ctx, nrCancel, rw := newrelic.StartTransaction(ctx, rw, r)
  29. ctx, ddCancel, rw := datadog.StartRootSpan(ctx, rw, r)
  30. cancel := func() {
  31. promCancel()
  32. nrCancel()
  33. ddCancel()
  34. }
  35. return ctx, cancel, rw
  36. }
  37. func StartDownloadingSegment(ctx context.Context) context.CancelFunc {
  38. promCancel := prometheus.StartDownloadingSegment()
  39. nrCancel := newrelic.StartSegment(ctx, "Downloading image")
  40. ddCancel := datadog.StartSpan(ctx, "downloading_image")
  41. cancel := func() {
  42. promCancel()
  43. nrCancel()
  44. ddCancel()
  45. }
  46. return cancel
  47. }
  48. func StartProcessingSegment(ctx context.Context) context.CancelFunc {
  49. promCancel := prometheus.StartProcessingSegment()
  50. nrCancel := newrelic.StartSegment(ctx, "Processing image")
  51. ddCancel := datadog.StartSpan(ctx, "processing_image")
  52. cancel := func() {
  53. promCancel()
  54. nrCancel()
  55. ddCancel()
  56. }
  57. return cancel
  58. }
  59. func SendError(ctx context.Context, errType string, err error) {
  60. prometheus.IncrementErrorsTotal(errType)
  61. newrelic.SendError(ctx, err)
  62. datadog.SendError(ctx, err)
  63. }
  64. func SendTimeout(ctx context.Context, d time.Duration) {
  65. prometheus.IncrementErrorsTotal("timeout")
  66. newrelic.SendTimeout(ctx, d)
  67. datadog.SendTimeout(ctx, d)
  68. }