Documentation
¶
Index ¶
- type CacheTracing
- func (c *CacheTracing) RecordDelete(ctx context.Context, key string, duration time.Duration, err error)
- func (c *CacheTracing) RecordError(span trace.Span, err error)
- func (c *CacheTracing) RecordGet(ctx context.Context, key string, hit bool, duration time.Duration, err error)
- func (c *CacheTracing) RecordHit(span trace.Span, hit bool)
- func (c *CacheTracing) RecordSet(ctx context.Context, key string, duration time.Duration, err error)
- func (c *CacheTracing) SetItemSize(span trace.Span, size int64)
- func (c *CacheTracing) StartSpan(ctx context.Context, operation, key string) (context.Context, trace.Span)
- type DBTracing
- func (d *DBTracing) RecordError(span trace.Span, err error)
- func (d *DBTracing) RecordQuery(ctx context.Context, operation string, table string, duration time.Duration, ...)
- func (d *DBTracing) SetRowsAffected(span trace.Span, rows int64)
- func (d *DBTracing) StartSpan(ctx context.Context, operation, table string) (context.Context, trace.Span)
- type HTTPTracing
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CacheTracing ¶
type CacheTracing struct {
// contains filtered or unexported fields
}
CacheTracing provides OpenTelemetry distributed tracing for cache operations.
It creates spans for cache operations (GET, SET, DELETE) with semantic conventions following OpenTelemetry standards for cache instrumentation. Spans include operation type, cache hit/miss status, and error information.
func NewCacheTracing ¶
func NewCacheTracing(tracer trace.Tracer) *CacheTracing
NewCacheTracing initializes cache tracing instrumentation.
The tracer parameter should be obtained from a configured TracerProvider. The resulting CacheTracing instance can be safely reused across multiple cache clients (Redis, Memcached, etc.).
Example:
tracer := otel.Tracer("myapp/cache")
cacheTracing := NewCacheTracing(tracer)
Production recommendations:
- Instantiate once per application.
- Trace all cache operations for complete visibility.
- Correlate with cache metrics for performance analysis.
func (*CacheTracing) RecordDelete ¶
func (c *CacheTracing) RecordDelete( ctx context.Context, key string, duration time.Duration, err error, )
RecordDelete creates and records a complete cache DELETE operation span.
This is a convenience method that creates a span, records the duration, and handles errors in a single call.
Example:
start := time.Now() err := redis.Del(ctx, "user:123") cacheTracing.RecordDelete(ctx, "user:123", time.Since(start), err)
For more control over span lifecycle, use StartSpan() instead.
func (*CacheTracing) RecordError ¶
func (c *CacheTracing) RecordError(span trace.Span, err error)
RecordError records an error in the current span.
This sets the span status to Error and records the error message as a span event. Call this whenever a cache operation fails.
Example:
ctx, span := cacheTracing.StartSpan(ctx, "SET", "user:123")
defer span.End()
err := redis.Set(ctx, key, value, ttl)
if err != nil {
cacheTracing.RecordError(span, err)
return err
}
Production recommendations:
- Always record errors for failed operations.
- Combine with metrics error counters for alerting.
func (*CacheTracing) RecordGet ¶
func (c *CacheTracing) RecordGet( ctx context.Context, key string, hit bool, duration time.Duration, err error, )
RecordGet creates and records a complete cache GET operation span.
This is a convenience method that creates a span, records the duration, hit/miss status, and handles errors in a single call.
Example:
start := time.Now() value, err := redis.Get(ctx, "user:123") hit := err == nil cacheTracing.RecordGet(ctx, "user:123", hit, time.Since(start), err)
For more control over span lifecycle, use StartSpan() instead.
Production recommendations:
- Use this for simple GET operations.
- For complex multi-step operations, use StartSpan().
func (*CacheTracing) RecordHit ¶
func (c *CacheTracing) RecordHit(span trace.Span, hit bool)
RecordHit records whether a cache operation resulted in a hit or miss.
This is typically used with GET operations after calling StartSpan().
Example:
ctx, span := cacheTracing.StartSpan(ctx, "GET", "user:123")
defer span.End()
value, err := redis.Get(ctx, "user:123")
if err == redis.Nil {
cacheTracing.RecordHit(span, false)
} else if err == nil {
cacheTracing.RecordHit(span, true)
}
func (*CacheTracing) RecordSet ¶
func (c *CacheTracing) RecordSet( ctx context.Context, key string, duration time.Duration, err error, )
RecordSet creates and records a complete cache SET operation span.
This is a convenience method that creates a span, records the duration, and handles errors in a single call.
Example:
start := time.Now() err := redis.Set(ctx, "user:123", userData, ttl) cacheTracing.RecordSet(ctx, "user:123", time.Since(start), err)
For more control over span lifecycle, use StartSpan() instead.
Production recommendations:
- Use this for simple SET operations.
- Record TTL information if relevant to debugging.
func (*CacheTracing) SetItemSize ¶
func (c *CacheTracing) SetItemSize(span trace.Span, size int64)
SetItemSize records the size of a cache item.
This is useful for tracking memory usage and identifying large items that may impact cache performance.
Example:
ctx, span := cacheTracing.StartSpan(ctx, "GET", "user:123")
defer span.End()
value, err := redis.Get(ctx, "user:123")
if err == nil {
cacheTracing.SetItemSize(span, int64(len(value)))
}
func (*CacheTracing) StartSpan ¶
func (c *CacheTracing) StartSpan(ctx context.Context, operation, key string) (context.Context, trace.Span)
StartSpan creates a new span for a cache operation.
The span should be ended with span.End() when the operation completes. Use RecordHit() or RecordError() to add operation-specific attributes.
Example:
ctx, span := cacheTracing.StartSpan(ctx, "GET", "user:123")
defer span.End()
value, err := redis.Get(ctx, "user:123")
if err == redis.Nil {
cacheTracing.RecordHit(span, false) // miss
} else if err != nil {
cacheTracing.RecordError(span, err)
} else {
cacheTracing.RecordHit(span, true) // hit
}
Production recommendations:
- Always call span.End() using defer.
- Record hit/miss status for GET operations.
- Use consistent operation and key patterns for aggregation.
type DBTracing ¶
type DBTracing struct {
// contains filtered or unexported fields
}
DBTracing provides OpenTelemetry distributed tracing for database operations.
It creates spans for database queries with semantic conventions following OpenTelemetry standards for database client instrumentation. Spans include operation type, table name, duration, and error information.
func NewDBTracing ¶
NewDBTracing initializes database tracing instrumentation.
The tracer parameter should be obtained from a configured TracerProvider. The resulting DBTracing instance can be safely reused across multiple database clients and connection pools.
Example:
tracer := otel.Tracer("myapp/db")
dbTracing := NewDBTracing(tracer)
Production recommendations:
- Instantiate once per process or connection pool.
- Create spans for all database operations.
- Correlate with DB metrics for complete observability.
func (*DBTracing) RecordError ¶
RecordError records an error in the current span.
This sets the span status to Error and records the error message as a span event. Call this whenever a database operation fails.
Example:
ctx, span := dbTracing.StartSpan(ctx, "INSERT", "users")
defer span.End()
_, err := db.ExecContext(ctx, query, args...)
if err != nil {
dbTracing.RecordError(span, err)
return err
}
Production recommendations:
- Always record errors for failed operations.
- Combine with metrics error counters for alerting.
func (*DBTracing) RecordQuery ¶
func (d *DBTracing) RecordQuery( ctx context.Context, operation string, table string, duration time.Duration, err error, )
RecordQuery creates and records a complete database query span.
This is a convenience method that creates a span, records the duration, and handles errors in a single call. Use this when you want automatic span management.
Example:
start := time.Now() rows, err := db.QueryContext(ctx, "SELECT * FROM users") dbTracing.RecordQuery(ctx, "SELECT", "users", time.Since(start), err)
For more control over span lifecycle, use StartSpan() instead.
Production recommendations:
- Use this for simple query recording.
- For complex operations with multiple steps, use StartSpan().
func (*DBTracing) SetRowsAffected ¶
SetRowsAffected records the number of rows affected by a database operation.
This is useful for INSERT, UPDATE, DELETE operations to track the impact of the query.
Example:
result, err := db.ExecContext(ctx, "DELETE FROM users WHERE inactive = true")
if err == nil {
rowsAffected, _ := result.RowsAffected()
dbTracing.SetRowsAffected(span, rowsAffected)
}
func (*DBTracing) StartSpan ¶
func (d *DBTracing) StartSpan(ctx context.Context, operation, table string) (context.Context, trace.Span)
StartSpan creates a new span for a database operation.
The span should be ended with span.End() when the operation completes. Use RecordError() if the operation fails.
Example:
ctx, span := dbTracing.StartSpan(ctx, "SELECT", "users")
defer span.End()
rows, err := db.QueryContext(ctx, "SELECT * FROM users WHERE id = ?", id)
if err != nil {
dbTracing.RecordError(span, err)
return err
}
Production recommendations:
- Always call span.End() using defer.
- Record errors immediately when they occur.
- Use consistent operation and table names for better aggregation.
type HTTPTracing ¶
type HTTPTracing struct {
// contains filtered or unexported fields
}
HTTPTracing provides OpenTelemetry distributed tracing for HTTP requests.
It creates spans for each HTTP request with semantic conventions following OpenTelemetry standards for HTTP server instrumentation. Spans include request method, URL, status code, and error information.
func NewHTTPTracing ¶
func NewHTTPTracing(tracer trace.Tracer) *HTTPTracing
NewHTTPTracing initializes HTTP tracing instrumentation.
The tracer parameter should be obtained from a configured TracerProvider. The resulting HTTPTracing instance can be safely reused across multiple HTTP handlers and routers.
Example:
tracer := otel.Tracer("myapp/http")
httpTracing := NewHTTPTracing(tracer)
router.Use(httpTracing.Middleware())
Production recommendations:
- Instantiate once per application.
- Combine with HTTP metrics for complete observability.
- Use consistent span naming across services.
func (*HTTPTracing) Middleware ¶
func (h *HTTPTracing) Middleware() func(http.Handler) http.Handler
Middleware returns a Chi-compatible middleware that creates a span for each HTTP request.
This middleware uses LAZY ROUTE PATTERN CAPTURE to avoid cardinality explosion. It creates a temporary span at the start, executes the handler (allowing Chi to populate RouteContext), then updates the span with the correct route pattern.
The middleware:
- Extracts trace context from incoming request headers
- Creates a new span with temporary name
- Injects the span into the request context
- Executes the handler (Chi populates RouteContext during this)
- Updates span with correct route pattern
- Records request attributes (method, route pattern, status)
- Records errors if the status code indicates failure
- Properly ends the span after the request completes
Example:
router := chi.NewRouter()
router.Use(httpTracing.Middleware()) // Global middleware
router.Get("/users/{id}", handler) // Will be traced as "GET /users/{id}"
The span is automatically propagated through the context and can be accessed by downstream operations (DB queries, cache operations, etc.).
Production recommendations:
- Place this middleware early in the chain for complete coverage.
- Combine with metrics middleware for unified observability.
- Use trace sampling to control data volume in production.
func (*HTTPTracing) RecordRequest ¶
func (h *HTTPTracing) RecordRequest( ctx context.Context, method string, path string, statusCode int, duration time.Duration, ) (context.Context, trace.Span)
RecordRequest is a manual method to record HTTP request traces.
This is provided for compatibility with custom HTTP clients or situations where the middleware cannot be used. For most use cases, the Middleware() approach is recommended.
Example:
ctx, span := httpTracing.RecordRequest(ctx, "GET", "/api/users/{id}", 200, duration)
defer span.End()
Production recommendations:
- Prefer the middleware for automatic instrumentation.
- Use this for HTTP client calls or non-standard servers.