Skip to content

Plugins: Chore: Renamed instrumentation middleware to metrics middleware#8

Closed
ShashankFC wants to merge 1 commit into
mainfrom
plugins/rename-instrumentation-middleware-to-metrics-middleware
Closed

Plugins: Chore: Renamed instrumentation middleware to metrics middleware#8
ShashankFC wants to merge 1 commit into
mainfrom
plugins/rename-instrumentation-middleware-to-metrics-middleware

Conversation

@ShashankFC

@ShashankFC ShashankFC commented Feb 13, 2026

Copy link
Copy Markdown

User description

Test 3nn

Summary by CodeRabbit

  • New Features

    • Added context-aware logging that enriches request logs with plugin ID, endpoint name, data source information, and user login details for improved plugin operation visibility and debugging.
  • Refactor

    • Refactored plugin middleware architecture to better separate logging and metrics concerns, improving code maintainability and clarity.

✏️ Tip: You can customize this high-level summary in your review settings.

nn---n*Replicated from [ai-code-review-evaluation/grafana-coderabbit#3](https://github.com/ai-code-review-evaluation/grafana-coderabbit/pull/3)*

CodeAnt-AI Description

Rename instrumentation middleware to metrics and add contextual logger middleware for plugin requests

What Changed

  • Middleware renamed: InstrumentationMiddleware → MetricsMiddleware; public constructor now exposed as NewMetricsMiddleware so metrics for plugin request count, duration, and size continue to be recorded under the new name
  • Added a separate ContextualLogger middleware that injects plugin-specific attributes (plugin ID, endpoint, datasource name/UID, and user login) into request context so downstream log entries include those details
  • Logger interface and test logger updated to accept flexible argument types and provide FromContext support; Logger middleware now uses the contextual logger from request context when emitting completion logs
  • Tests and middleware registration updated to use the new names and middleware ordering

Impact

✅ Clearer plugin logs with plugin, endpoint, datasource and user context
✅ Metrics collection for plugin requests preserved under the MetricsMiddleware name
✅ More reliable contextual logging available to downstream plugin handlers

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

…are (#76186)

* Plugins: Chore: Renamed instrumentation middleware to metrics middleware

* Removed repeated logger attributes in middleware and contextual logger

* renamed loggerParams to logParams

* PR review suggestion

* Add contextual logger middleware

* Removed unused params from logRequest

* Removed unwanted changes

* Safer FromContext method

* Removed traceID from logParams
@ShashankFC

Copy link
Copy Markdown
Author

@CodeAnt-AI: review

@codeant-ai

codeant-ai Bot commented Feb 13, 2026

Copy link
Copy Markdown

CodeAnt AI is running the review.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Feb 13, 2026
Comment on lines +60 to +67
return m.next.SubscribeStream(ctx, req)
}

func (m *ContextualLoggerMiddleware) PublishStream(ctx context.Context, req *backend.PublishStreamRequest) (*backend.PublishStreamResponse, error) {
return m.next.PublishStream(ctx, req)
}

func (m *ContextualLoggerMiddleware) RunStream(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The contextual logger middleware instruments only query, resource, health, and metrics calls, but not streaming endpoints, so logs produced during subscribe/publish/run stream operations will lack the plugin, endpoint, data source, and user context that callers would reasonably expect given the middleware's purpose and comment; instrumenting the streaming methods with instrumentContext fixes this inconsistency. [logic error]

Severity Level: Major ⚠️
- ⚠️ Streaming plugin requests lack pluginId and endpoint log context.
- ⚠️ Harder to debug issues in live/streaming plugin features.
Suggested change
return m.next.SubscribeStream(ctx, req)
}
func (m *ContextualLoggerMiddleware) PublishStream(ctx context.Context, req *backend.PublishStreamRequest) (*backend.PublishStreamResponse, error) {
return m.next.PublishStream(ctx, req)
}
func (m *ContextualLoggerMiddleware) RunStream(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {
ctx = instrumentContext(ctx, "subscribeStream", req.PluginContext)
return m.next.SubscribeStream(ctx, req)
}
func (m *ContextualLoggerMiddleware) PublishStream(ctx context.Context, req *backend.PublishStreamRequest) (*backend.PublishStreamResponse, error) {
ctx = instrumentContext(ctx, "publishStream", req.PluginContext)
return m.next.PublishStream(ctx, req)
}
func (m *ContextualLoggerMiddleware) RunStream(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {
ctx = instrumentContext(ctx, "runStream", req.PluginContext)
Steps of Reproduction ✅
1. Observe middleware wiring in
`pkg/services/pluginsintegration/pluginsintegration.go:155-162`: `CreateMiddlewares`
builds the default plugin client middleware chain including
`clientmiddleware.NewContextualLoggerMiddleware()` at line 160, and passes that into
`client.NewDecorator` in `NewClientDecorator` at lines 149-152.

2. Inspect
`pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go:26-37,39-57`:
`instrumentContext` enriches the context with `"endpoint"`, `"pluginId"`, and optional
`"dsName"`, `"dsUID"`, `"uname"`, and is called from `QueryData`, `CallResource`,
`CheckHealth`, and `CollectMetrics` before delegating to `m.next`.

3. Inspect the same file at lines 59-69 (the existing_code snippet): `SubscribeStream`,
`PublishStream`, and `RunStream` simply call
`m.next.SubscribeStream/PublishStream/RunStream(ctx, req, ...)` without invoking
`instrumentContext`, so the context passed to downstream middlewares and the plugin
implementation is not enriched for streaming calls.

4. Confirm that streaming endpoints are exercised in real code paths using the plugin
client: grep results show `SubscribeStream`/`PublishStream`/`RunStream` wired through the
plugin stack (e.g., `pkg/plugins/manager/client/decorator.go:70` defines `func (d
*Decorator) SubscribeStream(...)`, and multiple services and datasources implement these
methods such as `pkg/tsdb/loki/streaming.go:18` and
`pkg/services/live/runstream/manager.go:38`), meaning real streaming requests traverse the
same decorator/middleware chain but bypass contextual instrumentation in
`ContextualLoggerMiddleware` for those methods.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go
**Line:** 60:67
**Comment:**
	*Logic Error: The contextual logger middleware instruments only query, resource, health, and metrics calls, but not streaming endpoints, so logs produced during subscribe/publish/run stream operations will lack the plugin, endpoint, data source, and user context that callers would reasonably expect given the middleware's purpose and comment; instrumenting the streaming methods with `instrumentContext` fixes this inconsistency.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
👍 | 👎

@codeant-ai

codeant-ai Bot commented Feb 13, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Import collision & brittle type assertion
    The file's package is log and it also imports github.com/grafana/grafana/pkg/infra/log (same identifier). This is confusing and error-prone. Additionally the code does a concrete type assertion to *log.ConcreteLogger, which couples this wrapper to the infra package's concrete type. Both make the code brittle and harder to maintain.

  • Incorrect variadic usage
    The call to WithContextualAttributes is passing a slice (p) as a single argument instead of expanding it as variadic arguments. That will pass a []any value into the function, not the intended key/value pairs, so contextual attributes will not be attached as expected.

  • Removed contextual logging fields
    The new LoggerMiddleware no longer enriches logs with pluginId, endpoint, datasource (dsName, dsUID), username or traceID — that information was removed from logParams. Verify this change is intentional because it reduces the amount of request metadata in logs and may impact debugging and observability. Ensure the new ContextualLoggerMiddleware consistently adds those attributes before LoggerMiddleware runs.

  • Missing instrumentation
    The stream-related methods (SubscribeStream, PublishStream, RunStream) do not add contextual attributes to the request context. If plugin/request details are relevant for these endpoints, they should be instrumented similarly to QueryData/CallResource/CheckHealth/CollectMetrics.

  • Inconsistent naming / leftover identifier
    In NewMetricsMiddleware the local variable is named imw (instrumentation middleware) even though the type is MetricsMiddleware. This inconsistent naming is harmless but confusing and may hint at incomplete refactor. Consider renaming to match the new type to improve readability.

@codeant-ai

codeant-ai Bot commented Feb 13, 2026

Copy link
Copy Markdown

CodeAnt AI finished running the review.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in 2 weeks if no further activity occurs. Please feel free to give a status update or ping for review. Thank you for your contributions!

@github-actions github-actions Bot added the stale label Mar 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically closed because it has not had any further activity in the last 2 weeks. Thank you for your contributions!

@github-actions github-actions Bot closed this Mar 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant