newrelic.go 1.5 KB

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