Logs, metrics and traces
Logs, metrics and traces
Observability connects evidence about a system to the work it performs. Logs describe events, metrics summarize measurements, and traces link operations across a request path.
Use structured message templates with stable field names and an event ID, not arbitrary formatted messages as the sole evidence. Never record authorization headers, secrets, customer payloads or raw connection strings. Log a minimal allow-listed event; even correlation identifiers may be sensitive. A metric counter records nonnegative increments, an up/down counter records signed changes, and a histogram records individual observations such as durations. An observable gauge reports a current non-additive value through a collection callback; keep callbacks bounded and do not assume a fixed polling schedule. Aggregation, temporality and export depend on the configured collector. Local listeners do not prove delivery to a backend. Give instruments units and bounded dimensions such as outcome or route template, not user ID, full URL or trace ID; cardinality consumes storage and query resources. An ActivitySource creates an Activity when a listener requests it, so StartActivity may return null. An activity has a trace ID shared with its related spans and a distinct span ID. Parent context can propagate across calls; sampling and propagation need explicit policy. A trace ID is correlation, not authentication. OpenTelemetry collects and exports instrumentation through configured providers; the exporter, sampling, resource attributes, endpoint access, redaction and shutdown flush are separate configuration choices. The following examples use a capturing logger and local listeners with no OpenTelemetry exporter or remote destination. They check emitted values and relationships rather than random IDs or wall-clock durations. The separate lab at lab-fixtures/telemetry/console-export demonstrates a local OpenTelemetry 1.21.0 trace exporter; console output format and timestamps vary and are not graded byte-for-byte.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models, in-process integrations and actual runtime or UI tests are distinguished.
Capture structured event fields
Inspect the state object given to a controlled ILogger implementation. The fixture retains only approved keys.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires the ASP.NET Core 10 shared framework.
using System;using System.Collections.Generic;using Microsoft.Extensions.Logging;var logger = new CaptureLogger();logger.LogInformation(new EventId(10, "Reservation"), "Reservation {Outcome} for {Units} units", "accepted", 2);if (logger.Event != 10 || logger.Outcome != "accepted" || logger.Units != 2) throw new Exception("log contract");Console.WriteLine($"event={logger.Event}; outcome={logger.Outcome}; units={logger.Units}");sealed class CaptureLogger : ILogger { public int Event { get; private set; } public string? Outcome { get; private set; } public int Units { get; private set; } public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel level) => level != LogLevel.None; public void Log<TState>(LogLevel level, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { Event = eventId.Id; if (state is IEnumerable<KeyValuePair<string, object?>> fields) foreach (var pair in fields) { if (pair.Key == "Outcome") Outcome = pair.Value as string; if (pair.Key == "Units" && pair.Value is int n) Units = n; } }}Expected result (not executed):
event=10; outcome=accepted; units=2ILogger receives structured state; provider implementations determine storage and formatting. This minimal capturing logger is a test double, not a production logging provider.
Observe a parent-child activity relationship
Register a local listener for one source. Check IDs by relationship, never by fixed random text.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits.
using System;using System.Diagnostics;Activity.DefaultIdFormat = ActivityIdFormat.W3C;Activity.ForceDefaultIdFormat = true;using var source = new ActivitySource("ByteMind.Inventory");using var listener = new ActivityListener { ShouldListenTo = s => s.Name == "ByteMind.Inventory", Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded};ActivitySource.AddActivityListener(listener);using var parent = source.StartActivity("reserve") ?? throw new Exception("missing parent");using var child = source.StartActivity("validate") ?? throw new Exception("missing child");child.SetTag("outcome", "accepted");if (parent.TraceId != child.TraceId || parent.SpanId != child.ParentSpanId || parent.SpanId == child.SpanId) throw new Exception("trace relationship");Console.WriteLine("same trace: True; correct parent: True; distinct spans: True");Expected result (not executed):
same trace: True; correct parent: True; distinct spans: TrueThe listener samples both spans; the using declarations dispose child before parent. In a real process without a listener StartActivity may return null; propagation across a remote boundary must be tested separately.
Record a bounded counter and duration observations
Attach a local MeterListener before creating instruments. Feed synthetic durations rather than measured performance.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits.
using System;using System.Collections.Generic;using System.Diagnostics.Metrics;using var meter = new Meter("ByteMind.Inventory");using var listener = new MeterListener();int requests = 0;var durations = new List<int>();listener.InstrumentPublished = (instrument, owner) => { if (instrument.Meter.Name == "ByteMind.Inventory") owner.EnableMeasurementEvents(instrument);};listener.SetMeasurementEventCallback<int>((instrument, measurement, tags, state) => { if (instrument.Name == "inventory.requests") requests += measurement; if (instrument.Name == "inventory.duration") durations.Add(measurement);});listener.Start();var count = meter.CreateCounter<int>("inventory.requests", unit: "{request}");var latency = meter.CreateHistogram<int>("inventory.duration", unit: "ms");foreach (int ms in new[] { 10, 30, 50 }) { count.Add(1, new KeyValuePair<string, object?>("outcome", "ok")); latency.Record(ms);}if (requests != 3 || durations.Count != 3) throw new Exception("metric contract");Console.WriteLine($"requests={requests}; samples={string.Join(",", durations)} ms");Expected result (not executed):
requests=3; samples=10,30,50 msThe callback observes individual instrument measurements, not exporter-aggregated time series. Real concurrent callbacks need thread-safe state. A histogram does not automatically produce an exact percentile at the instrumentation site.
Apply the concept
Design instrumentation for ReserveStock: choose one log template, two bounded metric dimensions, one counter, one histogram, and a parent/child span pair. Remove user IDs, bearer tokens and request bodies.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Logs, metrics and traces — knowledge check
Apply the lesson concepts to the following scenarios.
Why use structured log placeholders?
Which is a bounded metric label?
Why may StartActivity return null?
What relationship should a parent and child share?
What does a local MeterListener establish?