Design a platform observability starter: spans, metrics, logs, and redaction.
- User
Design a platform observability starter: spans, metrics, logs, and redaction.
Assistant
Design a platform observability starter: spans, metrics, logs, and redaction.
The user wants to design a "Platform Observability Starter." This implies a foundational design for monitoring a software platform. The key components requested are:
Target Audience/Context: Likely a software engineer, architect, or platform team looking for a template or architectural pattern to implement observability in their backend services (probably microservices). The language is likely Go, Python, Java, or Node.js, but I should provide a language-agnostic conceptual design with a concrete example (perhaps in Go or Python as they are common). Let's stick to a conceptual approach with code snippets (Go is usually best for "platform" examples due to OpenTelemetry maturity, or Python for readability). I will use a conceptual structure and pseudo-code/Go snippets for clarity.
Core Concepts & Structure:
The "Three Pillars" (plus one):
Technology Stack:
Design Steps:
Drafting the Content - Section by Section:
main.go (or entrypoint): Setup OTel.middleware.go: Auto-instrumentation (start span, inject trace ID into logs).redaction.go: The logic to find patterns (regex for credit cards, emails) and replace with *****.Refining the "Redaction" Requirement:
SpanProcessor that filters attributes before they are sent to the collector.Structuring the Response:
Self-Correction/Review during drafting:
Detailed Implementation Details (Mental Draft):
core (if using Zap) or middleware that iterates over fields.SpanProcessor (specifically FilterSpanProcessor or wrapping the BatchSpanProcessor) to scrub attributes. Wait, a SpanProcessor is called on start and on end. Modifying the span in OnEnd is the right place to scrub before export.Final Polish:
(Self-Correction on Redaction Approach): Simply regex-ing everything is expensive. The design should note that redaction is best done via a schema (knowing which fields are sensitive) or a heuristic regex for unstructured strings.
Let's build the response around Go as the exemplar language because OpenTelemetry-Go is strictly typed and explicit, making the architecture easier to understand than dynamic languages.
Outline of the Output:
Let's write it. Designing an observability starter requires moving beyond "just logging" to building a correlated system where telemetry tells a story.
Below is a design blueprint for a Platform Observability Starter. It focuses on the intersection of OpenTelemetry (OTel) for the pipeline, Structured Logging for context, and a Sanitization Layer for safety.
Instead of treating logs, metrics, and traces as separate silos, we design them as a unified object model centered on the Request Context.
Before instrumenting code, we must define how to handle sensitive data. We implement a Redaction Interceptor.
The Logic:
sensitive:"true") to mask fields in structured logs.Pseudocode (The Scrubber):
var sensitivePatterns = []*regexp.Regexp{
regexp.MustCompile(`(?i)(password|passwd|pwd|secret|token|api_key)`),
regexp.MustCompile(`\b\d{16}\b`), // Basic Credit Card
}
func Redact(key string, value interface{}) interface{} {
for _, pattern := range sensitivePatterns {
if pattern.MatchString(key) {
return "[REDACTED]"
}
if strVal, ok := value.(string); ok {
if pattern.MatchString(strVal) {
return "[REDACTED]"
}
}
}
return value
}
Spans represent work. The golden rule here is Semantic Attributes. Don't create generic attributes; use standard conventions so your dashboards work automatically.
Key Attributes to Include:
service.name: The logical name of the service.service.version: Git SHA or semantic version.http.route: The matched route pattern (e.g., /users/:id), not the raw URL (which contains PII).The Span Pattern:
func ProcessOrder(ctx context.Context, orderID string) {
// Start a span with the naming convention: {Package}.{Function}
tracer := otel.Tracer("order-service")
ctx, span := tracer.Start(ctx, "OrderService.ProcessOrder")
defer span.End()
// Set attributes (Scrubbed!)
span.SetAttributes(
attribute.String("order.id", Redact("order.id", orderID).(string)),
attribute.String("operation.type", "payment"),
)
// Business Logic...
if err := chargeCard(); err != nil {
// Record error on the span
span.RecordError(err)
span.SetStatus(codes.Error, "Payment Failed")
}
}
Don't track everything. Start with the RED Method for services:
The Metric Pattern (OTel Metrics): Use a MeterProvider to create instruments. Avoid "hot loops" (don't create a new metric instrument inside a for loop; create them once globally).
var (
// Create once at startup
requestCounter, _ = meter.Int64Counter(
"http.server.requests",
metric.WithDescription("Count of HTTP requests"),
metric.WithUnit("1"),
)
requestDuration, _ = meter.Float64Histogram(
"http.server.duration",
metric.WithUnit("ms"),
)
)
func RecordMetric(ctx context.Context, route string, status int, duration float64) {
// Common labels
attrs := []attribute.KeyValue{
attribute.String("http.route", route),
attribute.Int("http.status_code", status),
}
// Record values
requestCounter.Add(ctx, 1, metric.WithAttributes(attrs...))
requestDuration.Record(ctx, duration, metric.WithAttributes(attrs...))
}
Logs must be structured (JSON) and must include the trace_id and span_id. This allows you to jump from a spike in a metric graph directly to the relevant log lines.
The Log Pattern: Inject the Trace Context into your logger middleware.
type Logger struct {
inner *slog.Logger
}
func (l *Logger) Info(ctx context.Context, msg string, fields map[string]interface{}) {
// 1. Extract Trace Context
spanCtx := trace.SpanContextFromContext(ctx)
// 2. Add Trace IDs to log fields if valid
if spanCtx.IsValid() {
fields["trace_id"] = spanCtx.TraceID().String()
fields["span_id"] = spanCtx.SpanID().String()
}
// 3. Redact sensitive fields in the payload
for k, v := range fields {
fields[k] = Redact(k, v)
}
// 4. Write structured log
l.inner.Info(msg, "args", fields)
}
Here is how you compose these elements into a functioning platform.
Use environment variables for backend configuration so the code remains portable.
OTEL_EXPORTER_OTLP_ENDPOINT: Where to send data (e.g., http://jaeger:4317 or https://ingest.signoz.io).LOG_LEVEL: info or debug.This is where the magic happens. A middleware wraps every incoming request to start the trace, inject it into the context, and auto-instrument logs.
Conceptual Middleware Flow:
trace_id into the Logger context.Do not write traces to disk files. Send them to a collector (OpenTelemetry Collector).
| Component | Tool/Library | Key Implementation Detail |
|---|---|---|
| Transport | OTLP (gRPC/HTTP) | Standard wire format for all telemetry. |
| Tracing | OpenTelemetry API | Ensure trace.SpanFromContext(ctx) is used everywhere. |
| Metrics | OTel Metrics API | Focus on Histograms for latency (p99 is vital). |
| Logging | Zap / Zerolog / Logrus | JSON output only. Must include trace_id. |
| Redaction | Custom Middleware | Regex replacement on http.url, request.body, and db.statement. |
| Resilience | OTel Collector | Handle retries and batching if the backend is down. |
When you view this trace in a UI (like Jaeger or Grafana), it should look like this:
{
"traceID": "7f3d8a...",
"operationName": "POST /login",
"startTime": 1698760000,
"duration": 45000, // 45ms
"tags": [
{ "key": "http.status_code", "value": 200 },
{ "key": "user.email", "value": "[REDACTED]" },
{ "key": "db.statement", "value": "SELECT * FROM users WHERE email = '[REDACTED]'" }
]
}