1
0

newrelic.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package newrelic
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/imgproxy/imgproxy/v3/config"
  8. "github.com/newrelic/go-agent/v3/newrelic"
  9. )
  10. type transactionCtxKey struct{}
  11. var (
  12. enabled = false
  13. newRelicApp *newrelic.Application
  14. )
  15. func Init() error {
  16. if len(config.NewRelicKey) == 0 {
  17. return nil
  18. }
  19. name := config.NewRelicAppName
  20. if len(name) == 0 {
  21. name = "imgproxy"
  22. }
  23. var err error
  24. newRelicApp, err = newrelic.NewApplication(
  25. newrelic.ConfigAppName(name),
  26. newrelic.ConfigLicense(config.NewRelicKey),
  27. func(c *newrelic.Config) {
  28. if len(config.NewRelicLabels) > 0 {
  29. c.Labels = config.NewRelicLabels
  30. }
  31. },
  32. )
  33. if err != nil {
  34. return fmt.Errorf("Can't init New Relic agent: %s", err)
  35. }
  36. enabled = true
  37. return nil
  38. }
  39. func Enabled() bool {
  40. return enabled
  41. }
  42. func StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  43. if !enabled {
  44. return ctx, func() {}, rw
  45. }
  46. txn := newRelicApp.StartTransaction("request")
  47. txn.SetWebRequestHTTP(r)
  48. newRw := txn.SetWebResponse(rw)
  49. cancel := func() { txn.End() }
  50. return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
  51. }
  52. func StartSegment(ctx context.Context, name string) context.CancelFunc {
  53. if !enabled {
  54. return func() {}
  55. }
  56. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  57. segment := txn.StartSegment(name)
  58. return func() { segment.End() }
  59. }
  60. return func() {}
  61. }
  62. func SendError(ctx context.Context, err error) {
  63. if !enabled {
  64. return
  65. }
  66. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  67. txn.NoticeError(err)
  68. }
  69. }
  70. func SendTimeout(ctx context.Context, d time.Duration) {
  71. if !enabled {
  72. return
  73. }
  74. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  75. txn.NoticeError(newrelic.Error{
  76. Message: "Timeout",
  77. Class: "Timeout",
  78. Attributes: map[string]interface{}{
  79. "time": d.Seconds(),
  80. },
  81. })
  82. }
  83. }