newrelic.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  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() 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. config := newrelic.NewConfig(name, conf.NewRelicKey)
  24. newRelicApp, err = newrelic.NewApplication(config)
  25. if err != nil {
  26. return fmt.Errorf("Can't init New Relic agent: %s", err)
  27. }
  28. newRelicEnabled = true
  29. return nil
  30. }
  31. func startNewRelicTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc) {
  32. txn := newRelicApp.StartTransaction("request", rw, r)
  33. cancel := func() { txn.End() }
  34. return context.WithValue(ctx, newRelicTransactionCtxKey, txn), cancel
  35. }
  36. func startNewRelicSegment(ctx context.Context, name string) context.CancelFunc {
  37. txn := ctx.Value(newRelicTransactionCtxKey).(newrelic.Transaction)
  38. segment := newrelic.StartSegment(txn, name)
  39. return func() { segment.End() }
  40. }
  41. func sendErrorToNewRelic(ctx context.Context, err error) {
  42. txn := ctx.Value(newRelicTransactionCtxKey).(newrelic.Transaction)
  43. txn.NoticeError(err)
  44. }
  45. func sendTimeoutToNewRelic(ctx context.Context, d time.Duration) {
  46. txn := ctx.Value(newRelicTransactionCtxKey).(newrelic.Transaction)
  47. txn.NoticeError(newrelic.Error{
  48. Message: "Timeout",
  49. Class: "Timeout",
  50. Attributes: map[string]interface{}{
  51. "time": d.Seconds(),
  52. },
  53. })
  54. }