newrelic.go 1.6 KB

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