Log Strategy Without Log Hell
local graph
Chapter 7 — Log Strategy Without Log Hell
Section titled “Chapter 7 — Log Strategy Without Log Hell”There’s a moment every observability journey reaches, a moment of profound frustration.
Two weeks after deploying metrics and traces, a developer notices something strange. The error rate dashboard shows a sudden spike in payment validation failures on a Tuesday afternoon. The orders_checkout_failures_total counter she added in Chapter 6 catches it immediately. Traces confirm the failures originate in the Orders service during checkout. But the span just shows status: error with a 400 response code, nothing about why it failed.
The developer opens the logs and finds gigabytes of text. Grepping for “payment” returns millions of results. Most are INFO messages saying “Processing payment.” Somewhere in that mountain of text is the actual error, but finding it is like searching for a specific grain of sand on a beach.
The team had instrumented everything. They just instrumented it wrong, and this is log hell, and this chapter shows you how to escape it.
Without structure and correlation, logs are noise. With the right approach, they become the definitive record that explains why your system behaved the way it did.
In Chapter 4, we built the telemetry skeleton, traces that show where time is spent. In Chapter 5, we instrumented the data layer so that database queries are no longer invisible. In Chapter 6, we added metrics that answer the questions of how many and how often. Now we complete the three pillars by adding Loki, Grafana’s horizontally scalable log aggregation system, analogous to Prometheus for logs. Where Prometheus indexes time-series metrics by label, Loki indexes log streams by label and stores log content cheaply on object storage. By the end of this chapter, when you click a span in Jaeger, you’ll see the exact log messages from that operation. When you search Loki for an error, you’ll find the trace that contains it. And when a Grafana dashboard alerts on a metric spike, your logs will tell you exactly what went wrong.
What this chapter covers:
- The anatomy of log hell and how teams create it
- Structured logging with the
tracingcrate (and why we don’t ship JSON over the wire) - Trace correlation: linking logs to spans via
trace_idandspan_id - Log levels: when to use ERROR, WARN, INFO, DEBUG, and TRACE
- What to log (and what never to log)
- The OpenTelemetry Logs SDK and OTLP export
- Integrating Loki with Grafana for log visualization
- Practical instrumentation of all four services
- The three pillars unified: the complete observability workflow
The Problem with Traditional Logging
Section titled “The Problem with Traditional Logging”Before we fix logging, we need to understand how teams create log hell. It’s rarely intentional; it emerges from well-meaning decisions that compound over time.
What Log Hell Looks Like
Section titled “What Log Hell Looks Like”Here’s a real scenario from OpenTel E-Commerce before this chapter. A checkout fails, and we search the logs:
2026-01-15T10:23:41.123Z Starting checkout for [email protected]2026-01-15T10:23:41.124Z Processing item 1 of 32026-01-15T10:23:41.125Z Processing item 2 of 32026-01-15T10:23:41.126Z Processing item 3 of 32026-01-15T10:23:41.127Z Validating products...2026-01-15T10:23:41.234Z Product validation complete2026-01-15T10:23:41.235Z Reserving stock...2026-01-15T10:23:41.456Z Stock reserved successfully2026-01-15T10:23:41.457Z Creating order...2026-01-15T10:23:41.890Z Error: payment validation failed2026-01-15T10:23:41.891Z Rolling back...2026-01-15T10:23:42.012Z Checkout failedThese are the logs you’d turn to after the traces and metrics point you to a failing checkout. Your traces flow through OpenTelemetry to Jaeger. Your metrics flow through OpenTelemetry to Prometheus. But your logs? They’re raw eprintln! output dumped to stdout, completely outside the telemetry pipeline. There’s no request ID, no correlation token, nothing to tie these lines to a specific checkout attempt or connect them back to a trace. If 100 checkouts happen simultaneously, these lines interleave into chaos with nothing to group them. The error message “payment validation failed” is bare text, but what failed? Why? What was the payment method? The amount? Lines like “Processing item 1 of 3” are pure noise, and every line looks equally important because there’s no severity distinction. The third pillar, the one that should answer why, is broken because it hasn’t joined the OpenTelemetry ecosystem yet.
Now multiply this by four services, dozens of endpoints, and thousands of requests per minute. Welcome to log hell.
Production reality check: In real-world production systems, operators typically only enable WARN and ERROR logs. The hot-path INFO/DEBUG chatter shown above (“Processing item 1 of 3”) would be filtered out entirely. Section 7.3 covers level discipline, and Section 7.4 shows how to flip levels dynamically without a redeploy.
The Five Paths to Log Hell
Section titled “The Five Paths to Log Hell”Teams arrive at log hell via predictable paths.
Path 1: Unstructured Text The road to hell is paved with println!. Text like println!("Payment failed for user {}", email) resists querying. You can grep, but you can’t aggregate. You can’t ask “how many payment failures occurred by payment method in the last hour?” because payment method isn’t a field; it’s buried in prose.
Path 2: No Correlation A tracing::info!("Processing order") in one function and a tracing::error!("Database insert failed") fifty lines later in another function are orphans without trace or request IDs. When interleaved with logs from other requests, you can’t reconstruct the sequence. Was this error from the same request that was already being processed? Who knows.
Path 3: Wrong Granularity Logging inside loops creates 2N entries for N items. An order with 50 items generates 100 logs saying essentially nothing. During an incident, this noise buries the signal.
Path 4: Missing Context A line like tracing::error!("Validation failed") creates more questions than it answers. Validation of what? By which rule? For which field?
Path 5: Excessive Verbosity Eight DEBUG lines for a single function call, entering, each parameter, calling gateway, response received, parsing response, response parsed, exiting, reads like a paranoid developer’s diary. In production at INFO level, it’s invisible. But when you enable DEBUG to investigate an issue, you’re immediately drowning.
The solution is discipline and standards. Every log entry must be labeled. Every chain of causation must be preserved. Every field must be structured for machine parsing.
Structured Logging with Trace Context
Section titled “Structured Logging with Trace Context”Unstructured logs resist querying, aggregation, and correlation. Structured logs with typed fields, consistent naming, and machine parseable formats are the foundation of effective observability.
Structured Records as the Universal Format
Section titled “Structured Records as the Universal Format”Modern log aggregation systems, Loki, Elasticsearch, CloudWatch, expect structured data rather than free-form text. The JSON example below is a conceptual view of the fields we want to capture; the actual transport varies by backend. In our pipeline (built in Section 7.4), the Rust services export OpenTelemetry LogRecord objects over OTLP, and Loki natively ingests those records, promoting selected attributes (like service.name) to indexed labels and storing the rest as structured metadata. We are not serializing JSON log lines onto stdout for Loki to scrape. Read the JSON below as “these are the fields each log record carries”:
{ "timestamp": "2026-01-15T10:23:41.890123Z", "level": "ERROR", "target": "orders::handlers::checkout", "message": "Payment validation failed", "service": "orders", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "00f067aa0ba902b7", "payment.method": "card", "payment.card_brand": "visa", "payment.amount": "149.99", "error.type": "validation", "error.code": "CARD_EXPIRED"}This log entry answers every question immediately. What happened? Payment validation failed. When? 2026‑01‑15T10:23:41.890123Z. Where? Orders service, checkout handler. Which request? Trace 4bf92f35..., span 00f067aa.... Why? Card expired. What context? Visa card, $149.99. Compare this to “Error: payment validation failed” and the difference is night and day.
The Anatomy of a Good Log Entry
Section titled “The Anatomy of a Good Log Entry”Every production log entry should include these fields:
| Field | Purpose | Example |
|---|---|---|
timestamp | When (ISO 8601, UTC) | 2026‑01‑15T10:23:41.890123Z |
level | Severity classification | ERROR, WARN, INFO |
target | Code location (module path) | orders::handlers::checkout |
message | Human-readable static description | "Payment validation failed" |
service | Service name (via Resource) | orders |
trace_id | Distributed trace correlation | 4bf92f3577b34da6... |
span_id | Span-level correlation | 00f067aa0ba902b7 |
| Domain fields | Context specific to the operation | order.total, error.code |
Table 7.1 – Standard fields in every production log entry
From eprintln! to Structured tracing
Section titled “From eprintln! to Structured tracing”Let’s transform a real piece of code from our Orders service. In our current codebase, the error path during stock reservation looks something like this:
// orders/src/handlers/orders.rs - Before (scattered, unstructured)Err(response) => { eprintln!("Failed to reserve stock for {}: {:?}", item.product_uuid, response); release_all_reserved_stock(&state,&reserved_items).await; return response;}After transformation:
// orders/src/handlers/orders.rs - After (structured, contextual)Err(response) => { tracing::warn!( product.uuid = %item.product_uuid, quantity = item.quantity, reserved_so_far = reserved_items.len(), "Stock reservation failed, initiating rollback" ); release_all_reserved_stock(&state,&reserved_items).await; return response;}The transformation involves three key changes. First, eprintln! becomes tracing::warn! with proper severity, captured by the logging pipeline. Second, inline text becomes structured fields: product.uuid, quantity, and reserved_so_far are now queryable. Third, error details move from the message into fields.
The tracing Crate’s Structured Approach
Section titled “The tracing Crate’s Structured Approach”Rust’s tracing crate, which we’ve been using since Chapter 4 for spans, provides first-class support for structured logging too. Fields use a concise syntax % for Display formatting, ? for Debug formatting, and no prefix for direct primitive values. So tracing::info!(order.number = %order_number, order.total = ?total, item_count = items.len(), "Order created") produces a log entry with three queryable fields and a static message.
The real power comes from span inheritance. In Rust’s tracing ecosystem, fields declared on a span are visible to subscribers (the fmt_layer for stdout, tracing‑opentelemetry for span exports) when logs are emitted within that span. With the OpenTelemetry log bridge we add in Section 7.4, the bridge attaches the active span’s trace context (trace_id / span_id) to every exported log record, but span attributes and log-record attributes remain distinct in the OTel data model.
Practically, that means: declare context once on the span, and you get two benefits. Locally, your console output and Jaeger span events show those fields. Across pillars, the bridge attaches trace_id / span_id to every log record so Loki can correlate the log back to the trace, even though the log record itself does not duplicate the span’s attributes.
// hash_email is defined in Section 7.6. For now, read it as// "a stable SHA-256 prefix of the email".#[instrument(fields(customer.email_hash = %hash_email(&request.customer_email)))]pub async fn create_order(...) { // Console (fmt_layer) and Jaeger span events see customer.email_hash. // Logs exported to Loki are correlated to this span via trace_id/span_id. tracing::info!("Starting checkout"); tracing::info!("Validating items");}This eliminates repetitive context for local subscribers; set it once at the span level, and they inherit it. We saw this pattern with #[instrument] in Chapters 4 and 5 for trace spans. Now the same mechanism enriches our logs.
Service-Level Context via Resource
Section titled “Service-Level Context via Resource”Some context applies to every log from a service: service name, version, environment. In Chapter 4, we configured this via the OpenTelemetry Resource. When logs are exported via OTLP, this resource metadata is automatically attached to every record. Section 7.4 then configures Loki to promote the OpenTelemetry resource attribute service.name into the Loki stream label service_name, which is what makes queries like {service_name="orders"} possible. Without that promotion step, the attribute present on each record (as structured metadata) but isn’t indexed as a stream label. Once promoted, you can filter by service_name without adding it to any individual tracing::info!() call.
Correlation IDs: Linking Logs to Traces
Section titled “Correlation IDs: Linking Logs to Traces”The most powerful feature of modern logging is correlation with distributed traces. When every log entry includes trace_id and span_id, you can click a span in Jaeger and see all logs from that operation, find an error in Loki and jump directly to the trace, or search logs by trace ID to reconstruct the entire request across all services.
Consider two error logs from different services at the same millisecond:
2026-01-15T10:23:41.890Z ERROR orders: Payment validation failed2026-01-15T10:23:41.890Z ERROR inventory: Stock check failedAre these from the same request? Different requests? Without trace_id, you’re guessing. With trace context attached, you’d immediately see that they carry different trace IDs, separate requests, and unrelated errors. Or perhaps the same trace ID, confirming they’re part of one cascading failure.
Automatic Context Propagation
Section titled “Automatic Context Propagation”Our telemetry pipeline from Chapter 4 already bridges Rust’s tracing ecosystem with OpenTelemetry via the tracing‑opentelemetry crate. The OpenTelemetry layer we configured ensures spans created by #[instrument] are exported to Jaeger. But our console fmt_layer doesn’t include trace IDs in the output by default. We’ll fix this in Section 7.4 when we build the complete logging pipeline by adding the OpenTelemetry Logs SDK that automatically embeds trace_id and span_id into every log exported to Loki.
The Click-Through Workflow
Section titled “The Click-Through Workflow”Once correlation is established, the debugging workflow becomes seamless, an alert fires, you query Loki for errors, find a trace_id, click through to Jaeger, and see the full request flow. We’ll walk through this complete workflow in Section 7.4 once the entire pipeline is operational. For now, understand that this workflow, metric detects, log identifies, and trace explains, are only possible with correlation. It’s the payoff for everything we’ve built across Chapters 4, 5, and 6.
Log Levels and Filtering
Section titled “Log Levels and Filtering”Not all logs are equally important. Log levels classify the importance and urgency of each entry, and getting them right is the difference between a useful logging system and noise.
The Five Levels
Section titled “The Five Levels”ERROR is reserved for actual failures that affect users or require action, but something broke that should not have broken. WARN covers degraded but recoverable conditions, approaching limits, and compensating actions. INFO captures significant business events: an order created, a stock reserved, and a payment confirmed. DEBUG holds internal state useful for developers, cache hits, intermediate calculations, and successful sub-operations. TRACE is the most verbose: function entry/exit, loop iterations, analysis, you’d only enable under rare, targeted debugging conditions.
When to Use Each Level
Section titled “When to Use Each Level”ERROR should be reserved for real failures. A database insert that throws an exception deserves ERROR, it’s unexpected and requires investigation. But is a user not found during login? That’s often a normal condition (a typo in an email belongs at INFO or DEBUG level).
// Good ERROR usage - something broketracing::error!( error.code = %e.code(), error.message = %e, order.number = %order_number, "Failed to persist order to database");
// Bad ERROR usage - expected conditiontracing::error!("User not found"); // This might be normalWARN covers degraded operation and compensating actions:
// System is stressed but functioningtracing::warn!( pool.active = pool.size(), pool.max = pool.max_size(), wait_ms = wait_duration.as_millis(), "Connection pool exhausted, request queued");
// Compensating action takentracing::warn!( product.uuid = %uuid, reserved_count = reserved_items.len(), "Stock reservation failed, releasing previous reservations");INFO captures business events worth knowing about:
// Significant business eventtracing::info!( order.number = %order_number, order.total = %total, item_count = items.len(), "Order created successfully");DEBUG is for developer focused troubleshooting. It’s where you log cache hits, intermediate states, and successful sub-operations that aren’t business events but help trace the logic flow during development. TRACE is the last resort, loop iterations, raw data dumps, things you’d only enable when everything else has failed to explain the problem.
When to Log What
Section titled “When to Log What”Always Log
Section titled “Always Log”Business events like state transitions that matter. When an order is created, paid, or shipped, log it at INFO with the relevant identifiers: order number, status, and total. When inventory changes, log the product UUID, the quantity change, and the remaining stock. These are the facts an incident investigation will rely on.
External service calls like request and response summaries (never full bodies). When OtelMart calls the Orders service or when Orders calls Inventory for stock reservation, log the method, path, response status, and duration. We already get automatic spans from reqwest‑tracing (Chapter 4), but spans are navigated visually in Jaeger one trace at a time. An INFO-level log lets you run aggregate queries in Loki across all requests. For example, with the OTLP-native ingestion configured in Section 7.4: {service_name="otelmart"} | downstream_status >= 500 finds every failed downstream call in the last hour.
Errors with context**,** like full diagnostic details. When a database operation fails, include the error type, the error code (for SQLx, this means the PostgreSQL error code we discussed in Chapter 5), the error message, and which table and operation were involved.
Authentication events like security audit trail. When a user authenticates (or fails to), log the hashed user ID, the authentication method, and the result. Never the raw email or password.
The Decision Framework
Section titled “The Decision Framework”Ask yourself whether it is a business event, an error, or a security event. Log at INFO. Would it help debug issues in development? Log at DEBUG. Is it a loop iteration or extremely verbose? Don’t log it (or TRACE at most). Otherwise, probably don’t log it.
Avoiding Log Spam
Section titled “Avoiding Log Spam”The Production Default Rule
Section titled “The Production Default Rule”In production, run with RUST_LOG=info. This captures all ERRORs (must investigate), all WARNs (should review), and all INFOs (understand system behavior). DEBUG and TRACE remain disabled but can be enabled dynamically for specific modules.
# Production defaultRUST_LOG=info
# Debug specific module without touching othersRUST_LOG=info,orders::handlers::checkout=debug
# Deep dive into database layerRUST_LOG=info,sqlx=debug,orders::db=traceYou’ll notice our docker‑compose.yml already sets RUST_LOG=info, otel::tracing=trace on each service, with INFO for business logic, and TRACE enabled only for the OpenTelemetry tracing internals to verify the pipeline works. We extend this to RUST_LOG=info,opentelemetry=off,otel::tracing=trace to prevent the logs-bridge feedback loop described in Section 7.4.
Aside, production alternative: filter at the Collector. In larger fleets, you may prefer to keep service binaries “thin”: send everything (including DEBUG-level log records) to a co-located OpenTelemetry Collector via OTLP and let the Collector’s filter and transform processors drop the noise before it reaches Loki, Jaeger, or Prometheus. When you need more detail during an incident, you change the Collector’s configuration rather than rebuilding services. This is infrastructure-side filtering on log records (not just spans), and it’s a different setup from the direct-to-Loki pipeline used throughout this chapter. We send logs straight from the Rust services to Loki via native OTLP ingestion to keep the development stack minimal. The OpenTelemetry Collector is covered in depth in a later chapter; for now, just be aware that this alternative exists.
Dynamic Log Levels Without Redeployment
Section titled “Dynamic Log Levels Without Redeployment”Our current telemetry.rs uses EnvFilter::try_from_default_env(), which reads RUST_LOG at startup. For true dynamic adjustment during an incident, you can use tracing_subscriber ‘s reload handle:
use tracing_subscriber::reload;
// Create a reloadable filterlet (filter, reload_handle) = reload::Layer::new( EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")));
// Store reload_handle in AppState, then expose an admin endpoint:async fn set_log_level( State(state): State<AppState>, body: String,) -> Result<&'static str, (StatusCode, String)> { // A malformed filter like "info,,," must NOT panic the service. // Parse first, return 400 on bad input, only then call reload. let new_filter = EnvFilter::try_new(&body) .map_err(|e| (StatusCode::BAD_REQUEST, format!("invalid filter: {e}")))?;
state .log_reload_handle .reload(new_filter) .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
tracing::info!(filter = %body, "Log level updated dynamically"); Ok("ok")}This follows the same fail-gracefully discipline used in earlier chapters: validate input at the boundary, return a 400 on bad input, and never let an admin endpoint panic a running service. Changing log levels without a restart is invaluable during production incidents. We won’t wire this endpoint into OpenTel E-Commerce here (it’s an exercise for the reader), but it’s worth knowing the mechanism exists.
Sampling for High-Volume Paths
Section titled “Sampling for High-Volume Paths”At high scale, logging every cache hit or heartbeat is expensive. Consider probability based sampling for verbose operations:
// Requires \`rand = "0.9"\` in the workspace \`Cargo.toml\`.// Our workspace already lists \`rand = "0.9.2"\` (see Section 7.4's// dependency listing) and each service inherits it via// \`rand = { workspace = true }\`.use rand::Rng;
/// Log at DEBUG level with samplingmacro_rules! debug_sampled { ($rate:expr, $($arg:tt)*) => { if tracing::enabled!(tracing::Level::DEBUG) && rand::rng().random_bool($rate) { tracing::debug!($($arg)*); } };}
// Usage: log 1% of cache hitsdebug_sampled!(0.01, cache.key = %key, "Cache hit");For production, consider tying sampling to the trace: if a trace is being sampled, log everything for that request; if not, skip DEBUG and TRACE levels. This gives you complete context for sampled requests while keeping log volume manageable.
Integrating Logs with OpenTelemetry
Section titled “Integrating Logs with OpenTelemetry”Log Exporters
Section titled “Log Exporters”Now we build the infrastructure. Our goal: logs flow from Rust services via OTLP directly to Loki, where Grafana queries and visualizes them. For our development setup, we’ll use Loki’s native OTLP endpoint (available in Loki 3.0+), which eliminates the need for a separate OpenTelemetry Collector.
Architecture Overview
Section titled “Architecture Overview”
figure 7.1
Figure 7.1 – The logging pipeline: a Rust service exports tracing events via OTLP/HTTP to Loki, which Grafana queries and visualizes
This mirrors the pattern we’ve established: traces go via OTLP gRPC to Jaeger (port 4317), metrics go via OTLP HTTP to Prometheus 3.0 (port 9090), and now logs go via OTLP HTTP to Loki (port 3100). Three pillars, three backends, one export protocol.
Adding the OpenTelemetry Logs SDK
Section titled “Adding the OpenTelemetry Logs SDK”First, update Cargo.toml with the logs-specific dependencies. The opentelemetry‑appender‑tracing crate bridges the tracing ecosystem with OpenTelemetry’s Logs API, converting tracing events into OTel log records. We also need sha2 and hex for PII hashing (used in Section 7.6):
# In workspace Cargo.toml, add to [workspace.dependencies]opentelemetry-appender-tracing = "0.31"sha2 = "0.10"hex = "0.4"The other OpenTelemetry dependencies (opentelemetry, opentelemetry_sdk, opentelemetry‑otlp, tracing‑opentelemetry) are already in place, as covered in Chapters 4 and 6. We need two changes: ensure opentelemetry‑otlp has the logs feature enabled, and add logs to opentelemetry_sdk ‘s features:
opentelemetry_sdk = { version = "0.31", features = [ "rt-tokio", # Tokio runtime support (Chapter 4) "metrics", # Metrics support (Chapter 6) "logs", # Logs support (new in Chapter 7)] }
opentelemetry-otlp = { version = "0.31", default-features = false, features = [ "grpc-tonic", # gRPC for traces (Chapter 4) "http-proto", # HTTP transport for metrics and logs exporters "reqwest-blocking-client", # HTTP client implementation "logs", # Logs export (new in Chapter 7)] }Note that http‑proto provides the HTTP transport layer and enables trace and metrics protocol support, but it does not enable logs. The logs feature must be listed separately—it gates the LogExporter builder and the underlying protobuf definitions for log records.
Why reqwest‑blocking‑client? It looks counterintuitive in a Tokio app, but in opentelemetry-sdk 0.31, the OTLP/HTTP exporters are driven by the SDK’s own batch-processor threads (see the version note below), not by the Tokio runtime. The blocking reqwest client is what those background threads expect; pairing the non-blocking reqwest client with the new batch processor will panic at startup because it tries to enter a Tokio runtime from a non-Tokio thread. If you upgraded from SDK 0.27–0.29 and kept the older async client, you’ll see exactly that panic.
Then, in each service’s Cargo.toml (orders, inventory, products, otelmart), add the new workspace dependency:
# Add to [dependencies] in each service's Cargo.tomlopentelemetry-appender-tracing = { workspace = true }sha2 = { workspace = true }hex = { workspace = true }Version note: This chapter uses opentelemetry‑sdk 0.31, which redesigned batch processors to spawn their own background threads. The with_batch_exporter(exporter) call no longer requires a runtime parameter like runtime::Tokio. If your Chapters 4 and 6 code uses the older with_batch_exporter(exporter, runtime::Tokio) signature from SDK 0.27–0.29, update all three providers to the new signature when adding logs support.
Updating telemetry.rs
Section titled “Updating telemetry.rs”Here’s the complete enhanced telemetry.rs with log export. This extends the Chapter 6 version by adding a LoggerProvider and the OpenTelemetryTracingBridge layer:
Each service has its own copy of telemetry.rs (e.g., orders/src/telemetry.rs, inventory/src/telemetry.rs). The code is identical across services—only the service_name argument differs. In a larger project, you might extract this into a shared library crate, but for our four-service setup, co-located copies keep each service self-contained.
// orders/src/telemetry.rs (same pattern in each service's telemetry.rs)
pub struct TelemetryGuard { // ... logger_provider: SdkLoggerProvider, // ← NEW in Chapter 7}
// ... TelemetryGuard::shutdown() adds logger_provider.shutdown()// before meter and tracer shutdown (reverse order of creation) ...
pubfninit_telemetry(service_name:&str)-> TelemetryGuard { // ... propagator, resource, traces/metrics endpoints unchanged from Chapter 6 ...
// Logs → Loki (HTTP on port 3100) ← NEW in Chapter 7 let logs_endpoint = std::env::var("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT") .unwrap_or_else(|_| "http://localhost:3100/otlp/v1/logs".into());
letlogger_provider=init_logger_provider(&logs_endpoint,&resource); // ← NEW
// OpenTelemetry logs layer — bridges tracing events to OTel logs ← NEW let otel_logs_layer = OpenTelemetryTracingBridge::new(&logger_provider);
let env_filter = EnvFilter::try_from_default_env() .unwrap_or_else(|_| EnvFilter::new("info,opentelemetry=off"));
// ... fmt_layer setup unchanged from Chapter 6 ...
tracing_subscriber::registry() .with(env_filter) .with(fmt_layer) .with(otel_logs_layer) // ← NEW .init();
TelemetryGuard { logger_provider }}Layer ordering matters when filters are attached to a specific layer**.** Adding EnvFilter directly to the registry as a top-level layer (as we do above with .with(env_filter)) filters every event the registry receives. The position of the .with(env_filter) call in the with(...) chain doesn’t change that, because registry-level layers are combined into a single dispatch. The ordering rule that does matter that is, when you bind a filter to a specific layer using layer.with_filter(…), that filter only gates that layer. To keep filtering uniform across console output, span export, and log export, we use a single registry-level EnvFilter; if you ever need different filtering per destination (for example, exporting DEBUG to Loki while showing only INFO on console), switch to per-layer filters using tracing_subscriber::filter::Targets on individual layers.
This means RUST_LOG=info,opentelemetry=off filters both console output and Loki export identically. The opentelemetry=off directive prevents the SDK’s internal diagnostics from being sent to the OpenTelemetryTracingBridge. Without it, when the batch channel fills up, the SDK’s otel_warn! macro emits a tracing::warn! that feeds back into the bridge, risking infinite recursion and stack overflow.
Dual-emit behavior**.** You may notice that both otel_trace_layer (from tracing‑opentelemetry) and otel_logs_layer (from opentelemetry‑appender‑tracing) receive the same tracing events. This is intentional; they serve complementary purposes:
tracing‑opentelemetryconverts events into OpenTelemetry span events, which appear inline within spans in Jaeger. This gives you logs attached to the specific operation that produced them.OpenTelemetryTracingBridgeconverts events into OpenTelemetry log records, which are exported to Loki as searchable, aggregatable structured logs.
The result: every tracing::info!() appears both as a span event in Jaeger (attached to the active span) and as a log record in Loki (queryable via LogQL). This dual visibility is a feature: Jaeger gives you logs in the context of a trace, while Loki gives you logs across all traces. The storage overhead is minimal because span events are lightweight metadata on existing spans.
The init_meter_provider function remains unchanged from Chapter 6. However, init_tracer_provider must be simplified: remove the subscriber setup (the tracing_subscriber::registry()...init() block, the EnvFilter, and the fmt_layer) because subscriber initialization is now centralized in init_telemetry where we combine all three layers. After the change, init_tracer_provider should only build and return the SdkTracerProvider, it no longer creates the tracing subscriber.
fninit_logger_provider(endpoint:&str,resource:&Resource)-> SdkLoggerProvider { let exporter = opentelemetry_otlp::LogExporter::builder() .with_http() .with_endpoint(endpoint) .build() .expect("Failed to create OTLP log exporter");
SdkLoggerProvider::builder() .with_resource(resource.clone()) .with_batch_exporter(exporter) .build()}The pattern mirrors init_tracer_provider and init_meter_provider exactly: an HTTP exporter pointing at the backend, a batch processor for efficiency, and the shared Resource for service metadata.
The OpenTelemetryTracingBridge is the critical piece. It sits in the tracing_subscriber layer stack alongside the fmt_layer (console output) and otel_trace_layer (span export). When a tracing event occurs (any tracing::info!(), tracing::error!(), etc.), the bridge converts it into an OpenTelemetry log record, complete with the current trace_id and span_id from the active span context. This is what gives us automatic trace correlation without any extra work in our application code.
Production hardening: enable experimental_use_tracing_span_context. By default, the bridge reads trace context from opentelemetry::Context::current(). For HTTP handlers in this chapter, that works because axum‑tracing‑opentelemetry middleware sets the OTel context per request. For background tasks, custom executors, or any code path where the OTel context isn’t pushed automatically, log records can be exported with a zero trace_id, and the click-through workflow silently breaks. The supported fix is to enable the experimental_use_tracing_span_context feature on opentelemetry‑appender‑tracing in your workspace Cargo.toml:
With the feature enabled, the bridge walks the active tracing span hierarchy and pulls the OTel SpanContext directly from the span’s extensions (where tracing‑opentelemetry writes it). This is the recommended path for #[instrument] + bridge code today; the experimental_* prefix signals the API may evolve, not that the behavior is unstable. The chapter’s example code works without it for the HTTP-only telemetry.rs paths shown, but you should turn it on before extending to background work.
Adding Loki to Docker Compose
Section titled “Adding Loki to Docker Compose”Add a Loki 3.0 service to docker‑compose.yml, exposed on port 3100 with a loki‑config.yaml volume mount. The key addition to each service’s environment is the logs endpoint:
environment: - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://jaeger:4317 # ← NEWEnsure Grafana depends on Loki. See the project’s docker‑compose.yml for the complete configuration.
Configuring Loki for OTLP Ingestion
Section titled “Configuring Loki for OTLP Ingestion”Create loki‑config.yaml to configure Loki’s OTLP receiver. Most of the file is standard Loki boilerplate (storage, schema, ring config). The critical section is limits_config.otlp_config:
limits_config: allow_structured_metadata: true # Required for trace_id in log metadata volume_enabled: true # Enables log volume exploration in Grafana otlp_config: # Accepts OpenTelemetry log records directly resource_attributes: attributes_config: - action: index_label # Promote to Loki stream label for fast queries attributes: - service.name # service.name → service_name in LogQLThis tells Loki to index the service.name OpenTelemetry resource attribute as a Loki stream label. With this in place, you can query logs with {service_name="orders"} in LogQL. Note that Loki converts dots to underscores in label names, so service.name in OTLP becomes service_name in LogQL.
Configuring Grafana Data Sources
Section titled “Configuring Grafana Data Sources”Create grafana‑datasources.yaml to auto provision all three backends (Prometheus, Loki, Jaeger). The Prometheus datasource is straightforward. Loki needs derivedFields so its trace_id structured metadata renders as a clickable link to Jaeger. Jaeger needs tracesToLogsV2 so spans link the other direction to Loki:
- name: Loki type: loki uid: loki jsonData: derivedFields: # Logs → Traces: make the trace_id field on each log record a link # that opens the matching trace in Jaeger. - name: TraceID matcherType: label matcherRegex: trace_id datasourceUid: jaeger url: '$${__value.raw}' urlDisplayLabel: 'View Trace'
- name: Jaeger type: jaeger uid: jaeger jsonData: tracesToLogsV2: # Traces → Logs: "Logs for this span" datasourceUid: loki # Must match Loki's uid above spanStartTimeShift: "-1m" # Widen window for clock skew spanEndTimeShift: "1m" customQuery: true query: '{service_name=~".+"} | trace_id = \`$${__span.traceId}\`' # $$ required — Grafana provisioning eats single $ during YAML parsingWith this configuration in place, Grafana enables bidirectional navigation between traces and logs:
Traces - > Logs. When you click a span in Grafana’s Jaeger view, a “Logs for this span” link runs the LogQL query above against Loki, filtering by trace_id. The time window is widened by ±1 minute to account for clock skew. One gotcha: the query uses $${__span.traceId} with a double dollar sign because Grafana provisioning YAML requires $$ to emit a literal $ for template variables. Without it, the link silently disappears.
Datasource ordering also matters: Loki must be provisioned before Jaeger because tracesToLogsV2 references Loki by its uid. Reversing the order causes a “data source not found” error.
Logs - > Traces. When Loki ingests logs via OTLP, trace_id is stored as structured metadata. The derivedFields block on the Loki datasource turns that field into a clickable link rendered in Grafana’s log detail panel; clicking it navigates to the matching trace in Jaeger. Without derivedFields, the trace_id is just text the click-through workflow this chapter promises does not work, and that failure mode is silent.
Verifying the Pipeline
Section titled “Verifying the Pipeline”Before instrumenting all four services, let’s verify that the pipeline works end to end. Start the stack:
docker compose up -dWait for all services to become healthy, then trigger a checkout through the OtelMart portal at http://localhost:4200 — browse products, add items to cart, and complete a checkout. This generates realistic telemetry across all four services. Alternatively, you can use curl or the generate_traffic.sh script from Chapter 6 to send requests directly.
Now open Grafana at http://localhost:3000, navigate to Explore, select the Loki datasource, and run:
{service_name="orders"}You should see structured log entries from the Orders service. If trace_id appears as a clickable link, the Jaeger integration is working. If you see no logs, check that Loki is running (curl http://localhost:3100/ready) and verify the OTEL_EXPORTER_OTLP_LOGS_ENDPOINT environment variable in your compose file.
Unified Observability Pipeline
Section titled “Unified Observability Pipeline”Now we apply structured logging consistently across all four services. Before writing code, let’s establish the standards that keep our logs consistent.
Logging Standards
Section titled “Logging Standards”Every service in OpenTel e-commerce follows these rules: messages are static strings with no interpolated IDs (use fields for identifiers). Field names use dot notation following OpenTelemetry conventions: order.number, product.uuid, error.type. Customer data is always hashed. Errors include error.type, error.code, and error.message as separate fields. External service calls log method, path, status, and duration. Business events use INFO level with clear state transitions.
These standards ensure that a developer jumping from Orders service logs to Inventory service logs sees a familiar structure. It’s the same principle as the trace taxonomy we defined in Chapter 4 —consistency across services enables cross-service analysis.
Migration Checklist: Replacing eprintln!
Section titled “Migration Checklist: Replacing eprintln!”Before adding new structured logging, audit the existing codebase for unstructured output. The Orders service currently uses eprintln! in several production code paths. Each needs to become a structured tracing call. For example:
// Before: unstructured, invisible to the telemetry pipelineeprintln!("Failed to call inventory service: {}", e);
// After: structured, exported to Loki with trace correlation.// \`type\` is a Rust keyword, so the raw-identifier \`r#type\` is required// in the field name. The exported attribute key is still \`error.type\`.tracing::error!( error.r#type = "http_client", error.message = %e, downstream.service = "inventory", "Failed to reach Inventory service");Apply this pattern to all eprintln! calls in ../orders.rs. The eprintln! calls in telemetry.rs shutdown methods are intentional and should stay — the tracing subscriber may already be partially shut down at that point.
Orders Service
Section titled “Orders Service”The Orders service is the most complex perspective in terms of logging. It orchestrates checkout by calling Products for validation, Inventory for stock reservation, and the database for persistence. Rather than reproducing the full handler (see orders/src/handlers/orders.rs), here are the key patterns:
Deferred span fields**:** The #[instrument] attribute declares fields that aren’t known yet:
#[instrument( name = "create_order", skip(state, request), fields( customer.email_hash = %hash_email(&request.customer_email), order.item_count = request.items.len(), order.number = tracing::field::Empty, // filled in later ))]pub async fn create_order(/* ... */) -> impl IntoResponse { // ... let order_number = db::generate_order_number(tx).await?; tracing::Span::current().record("order.number",ℴ_number); // From this point, every log in the span includes order.number}Log levels as state transitions**,** each phase of checkout gets an appropriate level:
tracing::info!("Order creation started"); // milestone
tracing::debug!(product.uuid = %uuid, "Product validated"); // per-item detail
tracing::warn!(price.submitted = %sub, price.actual = %act, // business failure "Price mismatch detected");
// \`type\` is a Rust keyword, so use the raw-identifier form \`r#type\`.tracing::error!(error.r#type = "database", error.message = %e, // infra failure "Database error during order creation");
tracing::info!(order.number = %num, order.total = %total, // success duration_ms = ms, "Order created successfully");Notice how logging and metrics work together. The checkout_attempts counter fires at the start, checkout_failures on error, and checkout_duration on success, the same counters from Chapter 6. The logs add the why: which product had a price mismatch, which item couldn’t be reserved, and what the database error was. Metrics answer “how often does checkout fail?” and logs answer “why did this specific checkout fail?”
Compensating Transaction Logging
Section titled “Compensating Transaction Logging”The release_all_reserved_stock function warrants special attention because a failure here results in leaked inventory. Note that while Section 7.3 advises against logging inside loops, this is the exception: each stock release is an independent network call to the Inventory service that can fail independently. A single batch log would hide which specific product failed to release, and a compensation failure for any product is a critical operational issue:
async fn release_all_reserved_stock(state: &AppState, items: &[(Uuid, i32)]) { tracing::info!(item_count = items.len(), "Releasing reserved stock");
for (product_uuid, quantity) in items { match release_stock(state, *product_uuid, *quantity).await { Ok(_) => { tracing::debug!( product.uuid = %product_uuid, quantity = quantity, "Stock released successfully" ); } Err(e) => { // This is serious - we have leaked inventory tracing::error!( product.uuid = %product_uuid, quantity = quantity, error.r#type = "compensation_failure", error.message = %e, "CRITICAL: Failed to release reserved stock" ); } } }
tracing::info!(item_count = items.len(), "Stock release complete");}The ERROR here is genuine: a compensation failure means reserved stock is stuck, affecting inventory accuracy. This is exactly the kind of distributed consistency issue we discussed in Chapter 3, now observable through our telemetry.
Why item_count, not released_count? release_stock swallows its own errors (it logs and returns () so a single failed release doesn’t abort the loop). At the end of the loop, we only know how many items we attempted; if any compensation failed, that error was already logged at ERROR severity above. Using released_count would imply successful releases, which we cannot guarantee from this position. To track real successes, you would need a counter incremented inside the Ok(_) arm, e.g., let mut released = 0u32; then released += 1; on success, and released_count = released on the final log.
Inventory Service
Section titled “Inventory Service”The Inventory service introduces a queryable outcome field. The operation.result deferred field records whether a reservation succeeded, had insufficient stock, or hit an error. A subtle but critical point: the OpenTelemetry log bridge attaches only the active span’s trace_id and span_id to each exported log record. It does not copy the span’s attributes onto the log record. So if you want operation.result to be queryable in Loki and visible on the span in Jaeger, you must record it in both places — once on the span via Span::current().record(...), and once on the log call as a field:
#[instrument( name = "reserve_stock", skip(pool), fields( otel.kind = "client", db.system.name = "postgresql", // Same conventions as Ch. 5 spans db.namespace = "inventory", product.uuid = %request.product_uuid, operation.result = tracing::field::Empty, ))]pub async fn reserve_stock(/* ... */) -> impl IntoResponse { // ... match result { Ok(true) => { tracing::Span::current().record("operation.result", "success"); tracing::info!( operation.result = "success", // also on the log record "Stock reserved successfully", ); } Ok(false) => { tracing::Span::current().record("operation.result", "insufficient_stock"); tracing::warn!( operation.result = "insufficient_stock", quantity.requested = qty, "Insufficient stock", ); } Err(e) => { tracing::Span::current().record("operation.result", "error"); tracing::error!( operation.result = "error", error.r#type = "database", error.message = %e, "Database error during stock reservation", ); } }}The operation.result field is now queryable in Loki as {service_name="inventory"} | operation_result="insufficient_stock" (Loki converts the dot to an underscore in field names). Without the duplicate on the log call, that query would return zero results even though the span shows the value correctly in Jaeger — a confusing failure mode worth remembering.
Products Service
Section titled “Products Service”The Products service demonstrates the same dual-record pattern with a boolean field (see products/src/handlers/products.rs). The single product lookup is a good example:
#[instrument( name = "get_product_by_id", skip(pool), fields(product.uuid = %uuid, product.found = tracing::field::Empty))]pub async fn get_product_by_id(/* ... */) -> impl IntoResponse { match db::get_product_by_uuid(&pool, uuid).await { Ok(Some(product)) => { tracing::Span::current().record("product.found", true); tracing::debug!( product.found = true, product.name = %product.product_name, "Product found", ); } Ok(None) => { tracing::Span::current().record("product.found", false); tracing::info!(product.found = false, "Product not found"); // INFO, not ERROR } // ... }}Notice that “Product not found” is at INFO, not ERROR. A missing product is a normal condition (the UUID might be invalid, or the product might have been removed). Logging it at ERROR would generate false alarms.
Gateway Service (OtelMart)
Section titled “Gateway Service (OtelMart)”The OtelMart gateway acts as a reverse proxy, using a generic proxy_request function in otelmart/src/proxy/mod.rs to handle all downstream communication. The key insight is the downstream.* field prefix:
// Successtracing::info!( downstream.service = %service_name, downstream.status = status.as_u16(), downstream.duration_ms = format!("{:.1}", duration * 1000.0), "Downstream call completed");
// Failuretracing::error!( error.r#type = "http_client", error.message = %e, downstream.service = %service_name, "Downstream service unavailable");Every proxied service (Orders, Products, Inventory) gets an identical downstream.* structured logging without duplicating instrumentation code. The TracingMiddleware on the HTTP client automatically creates client spans and injects trace context headers, so trace propagation works without explicit instrumentation in the proxy.
The Three Pillars Unified
Section titled “The Three Pillars Unified”With traces, metrics, and logs all implemented, let’s walk through a real incident investigation that demonstrates how they work together. This is the payoff for everything we’ve built across Chapters 4 through 7.
The Complete Workflow
Section titled “The Complete Workflow”Scenario: Tuesday at 3 PM, the error rate alert fires.
Step 1: Metric Detection. Grafana shows checkout_failures spiked from 1% to 8%. The RED dashboard we built in Chapter 6 reveals its specific failure.reason="validation" errors. The PromQL query rate(orders_checkout_failures_total{failure_reason="validation"}[5m]) shows the spike started at 2:55 PM.
Step 2: Log Investigation. Click through to Loki’s Explore view. With native OTLP ingestion, severity, trace IDs, and OTel attributes arrive as Loki structured metadata rather than as fields buried in a JSON body, so we don’t need a | json parsing stage. Query:
{service_name="orders"} |= "mismatch" | severity_text=~"WARN|ERROR"A note on these queries. With OTLP-native ingestion into Loki 3.0, OTel SeverityText lands are captured as the structured metadata field severity_text (uppercase: INFO, WARN, ERROR). Some Loki distributions also surface it as detected_level (lowercase) via auto-detection, and older JSON-line setups need | json | level="WARN". The queries below use severity_text because that is what we verified against the running stack in this chapter; adjust the field name to whatever your Loki instance actually exposes (check http://localhost:3100/loki/api/v1/labels and any record’s structured metadata).
The results show a pattern—dozens of log entries with the message “Price mismatch detected”, carried as a structured log record:
# Loki Explore view (one record, structured-metadata fields shown inline)2026-01-15T15:02:34.123Z service_name=orders severity_text=WARN body : "Price mismatch detected" trace_id : 4bf92f3577b34da6a3ce929d0e0e4736 span_id : 00f067aa0ba902b7 product.uuid : a7f3c5d2-1234-5678-9abc-def012345678 price.submitted : 29.99 price.actual : 34.99The structured fields tell us exactly what’s happening: customers are submitting orders with old prices (34.99. The validation logic we instrumented catches the discrepancy and rejects the order.
Step 3: Trace Correlation. Click the trace_id link in Grafana—the Loki datasource is configured to detect trace IDs from structured metadata and link directly to Jaeger.
The trace shows:
otelmart: POST /api/checkout [====] 45ms └─ orders: POST /orders [===] 40ms ├─ validate_product (HTTP GET products/...) [=] 15ms OK └─ (no further spans - validation failed early)The trace confirms: product validation succeeded (the product exists), but the price mismatch check caught the discrepancy before any stock was reserved. The order.number field is empty—the order was never created. The with_transaction span from Chapter 5 never appears because we rejected the request before reaching the database.
Step 4: Root Cause. Investigation reveals: the Product service updated prices at 2:55 PM. The frontend caches product data for 10 minutes. Users who loaded the catalog before 2:55 PM had stale prices until their cache expired around 3:05 PM. The metric confirms—the spike is exactly 10 minutes wide.
Step 5: Resolution. Short-term: reduce the frontend cache TTL to 2 minutes. Long term: implement cache invalidation when prices change.
Why No Single Pillar Suffices
Section titled “Why No Single Pillar Suffices”The workflow demonstrated something crucial: no single pillar could have diagnosed this on its own. Metrics without logs couldn’t explain why validation was failing, just that the failure count went up. Was it a code bug? A data issue? A downstream service failure? The metric doesn’t say. Logs without traces couldn’t show when in the request flow the failure occurred. Did it fail before or after the stock reservation? If so, we might have leaked inventory. Traces without logs wouldn’t show the actual mismatch values. The trace span shows “status: error” but doesn’t show the submitted price relative to the actual price.
Together, metrics detected the anomaly, logs identified the pattern, and the trace confirmed the behavior.
Searching Logs by Trace ID
Section titled “Searching Logs by Trace ID”With the logging pipeline in place and all services instrumented, searching logs by trace ID becomes the primary debugging workflow. The Grafana datasource configuration from Section 7.4 enables bidirectional navigation between traces and logs.
When an alert fires or you notice anomalous behavior, the workflow is straightforward:
- Start with a trace ID. If you have a trace ID from an error response, a metric alert, or a user report, search Loki directly:
This returns every log line from every service that participated in that trace, giving you a complete narrative of what happened across the distributed system.{service_name=~".+"} | trace_id = \`4bf92f3577b34da6a3ce929d0e0e4736\`
- Start with an error pattern. If you don’t have a trace ID yet, search for the error pattern first:
(See the note in Section 7.4 on{service_name="orders"} |= "mismatch" | severity_text=~"WARN|ERROR"
severity_textvsdetected_level; the exact label depends on your Loki version. With OTLP-native ingestion, you do not need a| jsonparsing stage; severity, trace IDs, and OTel attributes are already structured metadata.) Each result includes atrace_idin its structured metadata. In Grafana’s Loki Explore view, clicking thattrace_idvalue navigates directly to the corresponding trace in Jaeger. - Start with a trace in Jaeger. If you’re already viewing a trace in Grafana’s Jaeger datasource, click any span to reveal the “Logs for this span” link. This runs the LogQL query configured in
tracesToLogsV2(Section 7.4), filtering Loki logs by the span’s trace ID within a ±1-minute time window to account for clock skew. - Cross-service correlation. Because every service attaches the same
trace_idto its logs via theOpenTelemetryTracingBridge, you can see the complete request lifecycle:{service_name=~"otelmart|orders|inventory|products"} | trace_id = \`4bf92f3577b34da6a3ce929d0e0e4736\`
This shows the OtelMart gateway forwarding the request, the Orders service validating products, the Inventory service reserving stock, and the database operations—all unified by a single trace ID.
Best Practices for Production Logging
Section titled “Best Practices for Production Logging”Never Log
Section titled “Never Log”PII without redaction. Never log raw customer emails, addresses, or phone numbers. Instead, hash them: customer.email_hash = sha256_prefix(&customer.email). This preserves correlation (the same email produces the same hash) while protecting privacy.
Credentials, tokens, API keys. At most, log their existence or the last four characters: api_key.present = !api_key.is_empty().
Full request/response bodies. Log relevant fields instead: item count, calculated total, specific identifiers. Not the entire JSON payload.
High-cardinality identifiers in messages. A message like "Processing order {order_uuid}" creates millions of unique strings. Instead, keep the message static and put the UUID in a field: tracing::info!(order.uuid = %order_uuid, "Processing order"). Static messages enable log aggregation; interpolated ones defeat it.
Loop iterations. Don’t log inside loops in production. Log the batch: tracing::info!(item_count = items.len(), "Processing order items").
PII Protection
Section titled “PII Protection”Add helper functions for consistent field formatting across all services. Create a logging.rs module in each service (e.g., orders/src/logging.rs) and register it in main.rs with mod logging;:
// orders/src/logging.rs (same in each service)
use sha2::{Sha256, Digest};
/// Hash an email for logging (preserves privacy while enabling correlation)pub fn hash_email(email: &str) -> String { let mut hasher = Sha256::new(); hasher.update(email.as_bytes()); let result = hasher.finalize(); format!("sha256:{}", hex::encode(&result[..8]))}
/// Hash a numeric ID for loggingpub fn hash_id(id: i32) -> String { let mut hasher = Sha256::new(); hasher.update(id.to_le_bytes()); let result = hasher.finalize(); format!("sha256:{}", hex::encode(&result[..8]))}The sha2 and hex dependencies were already added to the workspace Cargo.toml and each service’s Cargo.toml in Section 7.4.
The hashing approach preserves correlation—the same email always produces the same hash—while ensuring that raw PII never appears in logs. When investigating an issue for a specific customer, you hash their email locally and search Loki for the hash. We truncate to 8 bytes (64 bits) for readability; for systems with billions of unique customers, consider using the full 32-byte hash to avoid collisions.
Lazy Formatting
Section titled “Lazy Formatting”Always use tracing ‘s lazy formatting rather than format!() in log macros:
// BAD: format!() runs even when DEBUG is disabledtracing::debug!("Item: {}", format!("{:?}",expensive_repr(&item)));
// GOOD: Only formatted if DEBUG is enabledtracing::debug!(item = ?item, "Processing item");The ? sigil tells tracing to use the Debug trait, but only if the log level is actually enabled. This can make a measurable difference in performance on hot paths.
Sensitive Data Redaction
Section titled “Sensitive Data Redaction”For defense-in-depth, create a redaction layer that detects sensitive patterns before they reach your log backend. The example below uses the standard-library LazyLock (stable since Rust 1.80), so no extra crates beyond regex are needed; if you target an older toolchain, replace LazyLock with once_cell::sync::Lazy and add once_cell to Cargo.toml. The regex crate is not used elsewhere in this chapter, so add it explicitly to the workspace Cargo.toml if you adopt this pattern:
# Add to [workspace.dependencies] in workspace Cargo.tomlregex = "1"# (only if you can't use std::sync::LazyLock):# once_cell = "1"use std::sync::LazyLock;use regex::Regex;
static CREDIT_CARD_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b") .expect("hard-coded regex must compile")});
pub fn redact_sensitive(input: &str) -> String { CREDIT_CARD_REGEX .replace_all(input, "[REDACTED_CARD]") .to_string()}This is a safety net, not a replacement for careful logging. If developers follow the “Never Log” rules earlier in this section, the redaction layer should never be triggered. But defense-in-depth matters: multiple layers of protection in case one fails.
Common Anti-Patterns and How to Fix Them
Section titled “Common Anti-Patterns and How to Fix Them”Let’s catalog the mistakes teams make so you can avoid them.
Anti-Pattern: Log and Throw. Logging an error where it occurs and where it’s handled doubles the number of errors in your logs. A helper function logs "Payment failed"; then the caller logs "Checkout failed" for the same error. Fix: propagate errors cleanly from helpers (using map_err), and log once at the boundary, but the handler where you actually decide what to do about it. Our Orders service in Section 7.4 demonstrates this: the create_order handler logs errors, but helper functions like validate_product and reserve_stock simply return Result types.
Anti-Pattern: Everything at INFO. When every internal step logs at INFO (“Starting validation”, “Validation step 1 complete”, “Validation step 2 complete”, “Validation complete”), your production logs are 90% noise. Fix: use DEBUG for internal steps, INFO only for the final outcome, and significant business events.
Anti-Pattern: DEBUG in Production. Running RUST_LOG=debug across all services generates massive volume, increases storage costs, and can actually mask errors in the noise. Fix: keep production at INFO. Enable DEBUG temporarily and for specific modules only using targeted filters like RUST_LOG=info,orders::handlers::checkout=debug.
Anti-Pattern: ERROR for Expected Conditions. A “user not found” during login, “insufficient stock” during reservation, or “product not found” during lookup are not errors. Logging them at ERROR creates alert fatigue. Fix: use INFO or DEBUG for expected conditions, ERROR only for genuine failures.
Anti-Pattern: Logging in Tight Loops. N logs for N iterations of a loop is a recipe for log explosion. Fix: log the batch, not each iteration. One log with item_count = 50 is worth more than 50 logs saying “Processing item.”
Anti-Pattern: Inconsistent Formats Across Services. When one service uses "time" and "lvl" while another uses "timestamp" and "level", cross-service log analysis becomes painful. Fix: Use the same telemetry.rs configuration across all services. With our shared init_telemetry() function, all four services produce identical log formats—a benefit of the shared infrastructure pattern we established in Chapter 4.
Anti-Pattern: No Retention Policy. Logs accumulate indefinitely until the disk fills. Fix: configure Loki retention in loki‑config.yaml:
limits_config: retention_period: 168h # 7 days
compactor: retention_enabled: true delete_request_store: filesystemSeven days is a reasonable default for development. Production systems typically keep 14–30 days of hot logs with longer archival for compliance.
Summary
Section titled “Summary”This chapter transformed OpenTel E-Commerce from a system with scattered print statements into a unified, queryable logging system integrated with distributed traces and metrics.
What we implemented:
We added the OpenTelemetry Logs SDK (opentelemetry‑appender‑tracing) alongside the existing trace and metric providers, creating a complete three-pillar telemetry pipeline in telemetry.rs. Each provider exports via OTLP to its respective backend—traces to Jaeger on port 4317 (gRPC), metrics to Prometheus on port 9090 (HTTP), and now logs to Loki on port 3100 (HTTP). Structured logging with consistent field naming (order.number, product.uuid, error.type) replaced unstructured text across all four services.
The OpenTelemetryTracingBridge layer automatically embeds trace_id and span_id in every log record, enabling the click-through workflow from Grafana dashboards to Loki logs to Jaeger traces. Grafana’s Loki datasource is configured to detect trace IDs from structured metadata and link directly to Jaeger.
The logging toolkit:
Business events (order created, stock reserved, checkout completed) are logged at INFO with relevant identifiers. Warnings cover degraded conditions and compensating actions. Errors are reserved for genuine failures—database errors, unreachable services, and compensation failures. Debug captures internal state for development troubleshooting. External service calls log method, status, and duration with a consistent downstream.* prefix.
Key principles:
Structure everything—no unstructured text in production. Correlate always—every log needs trace_id (the OpenTelemetryTracingBridge handles this automatically). Level appropriately—ERROR means action needed, not “something returned a non-200 status.” Hash PII—never log raw emails or customer identifiers. Log at boundaries—not in helper functions that propagate errors. Keep messages static—put variable data in structured fields.
The three pillars are complete:
| Pillar | Question Answered | Backend | Transport |
|---|---|---|---|
| Traces (Ch. 4) | Where did time go? How are services connected? | Jaeger | OTLP/gRPC -> port 4317 |
| Metrics (Ch. 6) | How many? How often? Is it getting worse? | Prometheus 3.0 | OTLP/HTTP -> port 9090 |
| Logs (Ch. 7) | What exactly happened? Why did it fail? | Loki 3.0 | OTLP/HTTP -> port 3100 |
Table 7.2 – The three pillars of observability with the question each answers, its backend, and its transport
The three pillars work in concert: metrics detect (error-rate spikes), logs identify (price mismatches on specific products), and traces explain (validation failed before stock reservation; no inventory leaked). This unified workflow turns incident investigation from hours of guesswork into minutes of systematic analysis.
In Chapter 8, we’ll build on this foundation to extract business intelligence from our telemetry. We’ll create dashboards that answer questions like “What’s our checkout conversion rate?” and “Which products have the highest cart abandonment?”—turning operational observability data into business insights.