newrelic.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/newrelic/go-agent/v3/newrelic"
  8. )
  9. const (
  10. newRelicTransactionCtxKey = ctxKey("newRelicTransaction")
  11. )
  12. var (
  13. newRelicEnabled = false
  14. newRelicApp *newrelic.Application
  15. )
  16. func initNewrelic() error {
  17. if len(conf.NewRelicKey) == 0 {
  18. return nil
  19. }
  20. name := conf.NewRelicAppName
  21. if len(name) == 0 {
  22. name = "imgproxy"
  23. }
  24. var err error
  25. newRelicApp, err = newrelic.NewApplication(
  26. newrelic.ConfigAppName(name),
  27. newrelic.ConfigLicense(conf.NewRelicKey),
  28. )
  29. if err != nil {
  30. return fmt.Errorf("Can't init New Relic agent: %s", err)
  31. }
  32. newRelicEnabled = true
  33. return nil
  34. }
  35. func startNewRelicTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  36. if !newRelicEnabled {
  37. return ctx, func() {}, rw
  38. }
  39. txn := newRelicApp.StartTransaction("request")
  40. txn.SetWebRequestHTTP(r)
  41. newRw := txn.SetWebResponse(rw)
  42. cancel := func() { txn.End() }
  43. return context.WithValue(ctx, newRelicTransactionCtxKey, txn), cancel, newRw
  44. }
  45. func startNewRelicSegment(ctx context.Context, name string) context.CancelFunc {
  46. if !newRelicEnabled {
  47. return func() {}
  48. }
  49. txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
  50. segment := txn.StartSegment(name)
  51. return func() { segment.End() }
  52. }
  53. func sendErrorToNewRelic(ctx context.Context, err error) {
  54. if newRelicEnabled {
  55. txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
  56. txn.NoticeError(err)
  57. }
  58. }
  59. func sendTimeoutToNewRelic(ctx context.Context, d time.Duration) {
  60. if newRelicEnabled {
  61. txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
  62. txn.NoticeError(newrelic.Error{
  63. Message: "Timeout",
  64. Class: "Timeout",
  65. Attributes: map[string]interface{}{
  66. "time": d.Seconds(),
  67. },
  68. })
  69. }
  70. }