Skip to content

Conversation

@hussam789
Copy link

@hussam789 hussam789 commented Oct 30, 2025

User description

PR #3


PR Type

Enhancement, Other


Description

  • Renamed InstrumentationMiddleware to MetricsMiddleware for clarity

  • Separated concerns: metrics tracking and contextual logging into distinct middleware

  • Added FromContext() method to Logger interface for context-based logger retrieval

  • Simplified LoggerMiddleware by removing duplicate context attributes

  • Updated all type signatures to use any instead of interface{}


Diagram Walkthrough

flowchart LR
  A["InstrumentationMiddleware<br/>metrics + logging"] -->|split| B["MetricsMiddleware<br/>prometheus metrics"]
  A -->|split| C["ContextualLoggerMiddleware<br/>context attributes"]
  D["Logger interface"] -->|add| E["FromContext method"]
  C -->|uses| E
  F["LoggerMiddleware"] -->|simplified| G["uses FromContext<br/>for context logger"]
Loading

File Walkthrough

Relevant files
Enhancement
ifaces.go
Add FromContext method and modernize type hints                   

pkg/plugins/log/ifaces.go

  • Added context import for new FromContext method
  • Changed all interface{} type hints to any for consistency
  • Added FromContext(ctx context.Context) Logger method to Logger
    interface
  • Updated PrettyLogger interface methods to use any instead of
    interface{}
+21/-16 
logger.go
Implement FromContext method for wrapper                                 

pkg/plugins/log/logger.go

  • Added context import
  • Implemented FromContext() method on grafanaInfraLogWrapper
  • Method safely extracts and wraps concrete logger from context
+12/-0   
logger_middleware.go
Simplify logger middleware and use FromContext                     

pkg/services/pluginsintegration/clientmiddleware/logger_middleware.go

  • Removed tracing import (no longer needed)
  • Simplified logRequest() signature by removing pluginCtx and endpoint
    parameters
  • Removed duplicate context attributes (pluginId, endpoint, user,
    datasource, traceID)
  • Changed to use FromContext() to retrieve contextual logger from
    context
  • Updated all middleware method calls to pass simplified parameters
+8/-25   
contextual_logger_middleware.go
New middleware for contextual logging                                       

pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go

  • New file: created dedicated middleware for adding contextual logger
    attributes
  • Implements NewContextualLoggerMiddleware() factory function
  • Adds plugin and request details (endpoint, pluginId, dsName, dsUID,
    uname) to context
  • Instruments context for QueryData, CallResource, CheckHealth, and
    CollectMetrics endpoints
+69/-0   
metrics_middleware.go
Rename to MetricsMiddleware and remove logging                     

pkg/services/pluginsintegration/clientmiddleware/metrics_middleware.go

  • Renamed InstrumentationMiddleware to MetricsMiddleware throughout
  • Renamed newInstrumentationMiddleware() to newMetricsMiddleware()
  • Renamed NewInstrumentationMiddleware() to NewMetricsMiddleware()
  • Removed log import (no longer needed)
  • Removed instrumentContext() function (moved to contextual logger
    middleware)
  • Updated all comments to reference MetricsMiddleware instead of
    InstrumentationMiddleware
  • Removed context instrumentation from instrumentPluginRequest() method
+18/-35 
Tests
fake.go
Add FromContext to test logger                                                     

pkg/plugins/log/fake.go

  • Added context import
  • Implemented FromContext() method on TestLogger for test compatibility
+6/-0     
metrics_middleware_test.go
Update test for renamed function                                                 

pkg/services/pluginsintegration/clientmiddleware/metrics_middleware_test.go

  • Updated test to call newMetricsMiddleware() instead of
    newInstrumentationMiddleware()
+1/-1     
Configuration changes
pluginsintegration.go
Update middleware registration and ordering                           

pkg/services/pluginsintegration/pluginsintegration.go

  • Updated middleware registration to use NewMetricsMiddleware() instead
    of NewInstrumentationMiddleware()
  • Added NewContextualLoggerMiddleware() to middleware stack
  • Reordered middleware: contextual logger now runs before logger
    middleware
+2/-1     

…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
@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing audit fields: The new logging path relies on context-derived attributes and no longer explicitly
includes user, pluginId, or endpoint in the emitted log, which may reduce audit trail
completeness unless the contextual logger guarantees these fields.

Referred Code
logParams := []any{
	"status", status,
	"duration", time.Since(start),
	"eventName", "grafana-data-egress",
	"time_before_plugin_request", timeBeforePluginRequest,
}
if status == statusError {
	logParams = append(logParams, "error", err)
}
m.logger.FromContext(ctx).Info("Plugin Request Completed", logParams...)
return err
Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status:
Potential PII logging: The contextual attributes add 'uname' (user login) to logging context which
could be considered PII, requiring confirmation that this is permitted and appropriately
protected.

Referred Code
	if pCtx.User != nil {
		p = append(p, "uname", pCtx.User.Login)
	}
	return log.WithContextualAttributes(ctx, p)
}
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Return the same logger instance

In TestLogger.FromContext, return the receiver f instead of a new TestLogger to
ensure logs are captured by the correct instance during tests.

pkg/plugins/log/fake.go [46-48]

 func (f *TestLogger) FromContext(_ context.Context) Logger {
-	return NewTestLogger()
+	return f
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the test utility TestLogger that would cause tests to fail or behave incorrectly, and the proposed fix is accurate.

Medium
General
Pre-allocate slice to avoid reallocations

In instrumentContext, pre-allocate the p slice with a capacity of 8 using
make([]any, 0, 8) to avoid potential reallocations and improve performance.

pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go [27-37]

 func instrumentContext(ctx context.Context, endpoint string, pCtx backend.PluginContext) context.Context {
-	p := []any{"endpoint", endpoint, "pluginId", pCtx.PluginID}
+	p := make([]any, 0, 8)
+	p = append(p, "endpoint", endpoint, "pluginId", pCtx.PluginID)
 	if pCtx.DataSourceInstanceSettings != nil {
 		p = append(p, "dsName", pCtx.DataSourceInstanceSettings.Name)
 		p = append(p, "dsUID", pCtx.DataSourceInstanceSettings.UID)
 	}
 	if pCtx.User != nil {
 		p = append(p, "uname", pCtx.User.Login)
 	}
 	return log.WithContextualAttributes(ctx, p)
 }
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion offers a valid micro-optimization by pre-allocating a slice to prevent reallocations, which improves performance, but the impact is minor.

Low
  • More

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants