newrelic.go 1.5 KB

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