Instrument logs metrics and traces
Instrument logs metrics and traces
Logs record events, metrics summarize measurements, and traces follow a request across operations using spans. A span describes a unit of work with timing, attributes and relationships; propagated context connects spans across service boundaries. Use structured logs, bounded metric labels and trace correlation. OpenTelemetry provides APIs, SDKs and exporters for these signals; this lesson uses local Go demonstrations rather than an installed SDK.
package main
import ( "bytes" "encoding/json" "fmt" "log/slog")
func main() { var b bytes.Buffer l := slog.New(slog.NewJSONHandler(&b, nil)) l.Info("request completed", "request_id", "demo-42", "status", 200) var record map[string]any if err := json.Unmarshal(b.Bytes(), &record); err != nil { panic(err) } fmt.Println(record["msg"], record["request_id"], record["status"])}The log has typed fields; decoding it avoids depending on time or field order. In production record the route template, outcome and trace/span IDs when available, not credentials or full payloads. A request ID can correlate logs but is not itself a distributed trace. Use a telemetry SDK and configured propagation for real spans.
Expected output:
request completed demo-42 200Aggregate bounded metric labels
package main
import ( "fmt")
func category(status int) string { switch { case status >= 200 && status < 300: return "success" case status >= 400 && status < 500: return "client_error" case status >= 500 && status < 600: return "server_error" default: return "other" }}func main() { counts := map[string]int{} for _, s := range []int{200, 201, 404, 503} { counts[category(s)]++ } fmt.Println(counts["success"], counts["client_error"], counts["server_error"])}This sequential counter model groups outcomes into four labels. A metric series is identified by its name and label combinations; adding unique request IDs can create enormous cardinality. Use counters for accumulated events and histograms for latency distributions; a production collector needs concurrency safety, export, sampling policy for traces and bounded queues. The map is not a Prometheus or OpenTelemetry instrument.
Expected output:
2 1 1Try it locally
Count completed requests with status 200, 500, 200 in two bounded outcome buckets (success and error). Print success count and error count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Service protocols and cloud 07: Instrument logs metrics and traces
Check the lesson objective before moving on.
Which metric label is generally dangerous for cardinality?
Does a request ID alone provide a distributed trace?