1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/newrelic.go

75 lines
1.6 KiB
Go
Raw Normal View History

2018-10-25 15:24:34 +02:00
package main
import (
"context"
2020-02-27 17:44:59 +02:00
"fmt"
2018-10-25 15:24:34 +02:00
"net/http"
"time"
2020-11-18 17:59:44 +02:00
"github.com/newrelic/go-agent/v3/newrelic"
2018-10-25 15:24:34 +02:00
)
var (
2018-10-29 14:04:47 +02:00
newRelicEnabled = false
2020-11-18 17:59:44 +02:00
newRelicApp *newrelic.Application
2018-10-25 15:24:34 +02:00
newRelicTransactionCtxKey = ctxKey("newRelicTransaction")
)
2020-02-27 17:44:59 +02:00
func initNewrelic() error {
2018-10-25 15:24:34 +02:00
if len(conf.NewRelicKey) == 0 {
2020-02-27 17:44:59 +02:00
return nil
2018-10-25 15:24:34 +02:00
}
name := conf.NewRelicAppName
if len(name) == 0 {
name = "imgproxy"
}
var err error
2020-11-18 17:59:44 +02:00
newRelicApp, err = newrelic.NewApplication(
newrelic.ConfigAppName(name),
newrelic.ConfigLicense(conf.NewRelicKey),
)
2018-10-25 15:24:34 +02:00
if err != nil {
2020-02-27 17:44:59 +02:00
return fmt.Errorf("Can't init New Relic agent: %s", err)
2018-10-25 15:24:34 +02:00
}
newRelicEnabled = true
2020-02-27 17:44:59 +02:00
return nil
2018-10-25 15:24:34 +02:00
}
2020-11-18 17:59:44 +02:00
func startNewRelicTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
txn := newRelicApp.StartTransaction("request")
txn.SetWebRequestHTTP(r)
newRw := txn.SetWebResponse(rw)
2018-10-25 15:24:34 +02:00
cancel := func() { txn.End() }
2020-11-18 17:59:44 +02:00
return context.WithValue(ctx, newRelicTransactionCtxKey, txn), cancel, newRw
2018-10-25 15:24:34 +02:00
}
func startNewRelicSegment(ctx context.Context, name string) context.CancelFunc {
2020-11-18 17:59:44 +02:00
txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
segment := txn.StartSegment(name)
2018-10-25 15:24:34 +02:00
return func() { segment.End() }
}
func sendErrorToNewRelic(ctx context.Context, err error) {
2020-11-18 17:59:44 +02:00
txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
2018-10-25 15:24:34 +02:00
txn.NoticeError(err)
}
func sendTimeoutToNewRelic(ctx context.Context, d time.Duration) {
2020-11-18 17:59:44 +02:00
txn := ctx.Value(newRelicTransactionCtxKey).(*newrelic.Transaction)
2018-10-25 15:24:34 +02:00
txn.NoticeError(newrelic.Error{
Message: "Timeout",
Class: "Timeout",
Attributes: map[string]interface{}{
"time": d.Seconds(),
},
})
}