newrelic.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. )
  28. if err != nil {
  29. return fmt.Errorf("Can't init New Relic agent: %s", err)
  30. }
  31. enabled = true
  32. return nil
  33. }
  34. func Enabled() bool {
  35. return enabled
  36. }
  37. func StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  38. if !enabled {
  39. return ctx, func() {}, rw
  40. }
  41. txn := newRelicApp.StartTransaction("request")
  42. txn.SetWebRequestHTTP(r)
  43. newRw := txn.SetWebResponse(rw)
  44. cancel := func() { txn.End() }
  45. return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
  46. }
  47. func StartSegment(ctx context.Context, name string) context.CancelFunc {
  48. if !enabled {
  49. return func() {}
  50. }
  51. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  52. segment := txn.StartSegment(name)
  53. return func() { segment.End() }
  54. }
  55. return func() {}
  56. }
  57. func SendError(ctx context.Context, err error) {
  58. if !enabled {
  59. return
  60. }
  61. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  62. txn.NoticeError(err)
  63. }
  64. }
  65. func SendTimeout(ctx context.Context, d time.Duration) {
  66. if !enabled {
  67. return
  68. }
  69. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  70. txn.NoticeError(newrelic.Error{
  71. Message: "Timeout",
  72. Class: "Timeout",
  73. Attributes: map[string]interface{}{
  74. "time": d.Seconds(),
  75. },
  76. })
  77. }
  78. }