From a5ace56be8644c725803e63798554a35eba27e79 Mon Sep 17 00:00:00 2001 From: Carl Bergquist Date: Wed, 7 Dec 2022 13:15:42 +0100 Subject: [PATCH] Plugins: Add username to datasource plugin logging (#59893) Co-authored-by: Marcus Efraimsson Signed-off-by: bergquist --- pkg/infra/log/requestTiming.go | 28 +++++++++++++++++++ pkg/middleware/logger.go | 2 ++ .../instrumentation/instrumentation.go | 7 +++++ 3 files changed, 37 insertions(+) create mode 100644 pkg/infra/log/requestTiming.go diff --git a/pkg/infra/log/requestTiming.go b/pkg/infra/log/requestTiming.go new file mode 100644 index 00000000000..a6b9c0bb5a1 --- /dev/null +++ b/pkg/infra/log/requestTiming.go @@ -0,0 +1,28 @@ +package log + +import ( + "context" + "time" +) + +type requestStartTimeContextKey struct{} + +var requestStartTime = requestStartTimeContextKey{} + +// InitCounter creates a pointer on the context that can be incremented later +func InitstartTime(ctx context.Context, now time.Time) context.Context { + return context.WithValue(ctx, requestStartTime, now) +} + +// TimeSinceStart returns time spend since the request started in grafana +func TimeSinceStart(ctx context.Context, now time.Time) time.Duration { + val := ctx.Value(requestStartTime) + if val != nil { + startTime, ok := val.(time.Time) + if ok { + return now.Sub(startTime) + } + } + + return 0 +} diff --git a/pkg/middleware/logger.go b/pkg/middleware/logger.go index 321daa210d0..4366ca45e45 100644 --- a/pkg/middleware/logger.go +++ b/pkg/middleware/logger.go @@ -35,6 +35,8 @@ func Logger(cfg *setting.Cfg) web.Middleware { // we have to init the context with the counter here to update the request r = r.WithContext(log.InitCounter(r.Context())) + // put the start time on context so we can measure it later. + r = r.WithContext(log.InitstartTime(r.Context(), time.Now())) rw := web.Rw(w, r) next.ServeHTTP(rw, r) diff --git a/pkg/plugins/backendplugin/instrumentation/instrumentation.go b/pkg/plugins/backendplugin/instrumentation/instrumentation.go index 5a42ef9a1fc..b9c12016272 100644 --- a/pkg/plugins/backendplugin/instrumentation/instrumentation.go +++ b/pkg/plugins/backendplugin/instrumentation/instrumentation.go @@ -51,6 +51,13 @@ func instrumentPluginRequest(ctx context.Context, cfg *config.Cfg, pluginCtx *ba "duration", elapsed, "pluginId", pluginCtx.PluginID, "endpoint", endpoint, + "eventName", "grafana-data-egress", + "insight_logs", true, + "since_grafana_request_started", log.TimeSinceStart(ctx, time.Now()), + } + + if pluginCtx.User != nil { + logParams = append(logParams, "uname", pluginCtx.User.Login) } traceID := tracing.TraceIDFromContext(ctx, false)