mirror of
https://github.com/imgproxy/imgproxy.git
synced 2025-02-07 11:36:25 +02:00
93 lines
1.8 KiB
Go
93 lines
1.8 KiB
Go
package newrelic
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/imgproxy/imgproxy/v3/config"
|
|
"github.com/imgproxy/imgproxy/v3/metrics/errformat"
|
|
"github.com/newrelic/go-agent/v3/newrelic"
|
|
)
|
|
|
|
type transactionCtxKey struct{}
|
|
|
|
var (
|
|
enabled = false
|
|
|
|
newRelicApp *newrelic.Application
|
|
)
|
|
|
|
func Init() error {
|
|
if len(config.NewRelicKey) == 0 {
|
|
return nil
|
|
}
|
|
|
|
name := config.NewRelicAppName
|
|
if len(name) == 0 {
|
|
name = "imgproxy"
|
|
}
|
|
|
|
var err error
|
|
|
|
newRelicApp, err = newrelic.NewApplication(
|
|
newrelic.ConfigAppName(name),
|
|
newrelic.ConfigLicense(config.NewRelicKey),
|
|
func(c *newrelic.Config) {
|
|
if len(config.NewRelicLabels) > 0 {
|
|
c.Labels = config.NewRelicLabels
|
|
}
|
|
},
|
|
)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("Can't init New Relic agent: %s", err)
|
|
}
|
|
|
|
enabled = true
|
|
|
|
return nil
|
|
}
|
|
|
|
func Enabled() bool {
|
|
return enabled
|
|
}
|
|
|
|
func StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
|
|
if !enabled {
|
|
return ctx, func() {}, rw
|
|
}
|
|
|
|
txn := newRelicApp.StartTransaction("request")
|
|
txn.SetWebRequestHTTP(r)
|
|
newRw := txn.SetWebResponse(rw)
|
|
cancel := func() { txn.End() }
|
|
return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
|
|
}
|
|
|
|
func StartSegment(ctx context.Context, name string) context.CancelFunc {
|
|
if !enabled {
|
|
return func() {}
|
|
}
|
|
|
|
if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
|
|
segment := txn.StartSegment(name)
|
|
return func() { segment.End() }
|
|
}
|
|
|
|
return func() {}
|
|
}
|
|
|
|
func SendError(ctx context.Context, errType string, err error) {
|
|
if !enabled {
|
|
return
|
|
}
|
|
|
|
if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
|
|
txn.NoticeError(newrelic.Error{
|
|
Message: err.Error(),
|
|
Class: errformat.FormatErrType(errType, err),
|
|
})
|
|
}
|
|
}
|