Standard Library

Structured Logging

Create useful, searchable logs with log/slog without exposing sensitive data.

What you will learn

By the end of this lesson, you will be able to:

  • configure text and JSON slog handlers;
  • use stable attributes instead of building messages with string concatenation;
  • choose useful log levels;
  • add request-scoped attributes without storing a logger implicitly in context;
  • avoid duplicated errors and sensitive-data leaks.

Mental model: logs are events

A human sentence is useful while reading one line. Structured attributes make millions of lines searchable and aggregatable.

Instead of this:

log.Printf("user %s completed lesson %s in %dms", userID, lessonID, elapsed)

record a stable event with fields:

logger.Info(
    "lesson completed",
    "user_id", userID,
    "lesson_id", lessonID,
    "duration_ms", elapsed.Milliseconds(),
)

Configure a logger once

func newLogger(environment string, level slog.Leveler) *slog.Logger {
    options := &slog.HandlerOptions{Level: level}

    var handler slog.Handler
    if environment == "production" {
        handler = slog.NewJSONHandler(os.Stdout, options)
    } else {
        handler = slog.NewTextHandler(os.Stdout, options)
    }

    return slog.New(handler)
}

Pass the logger explicitly to services that need it. This makes the dependency visible and testable.

Choose levels by meaning

  • Debug: detailed development diagnostics, normally disabled in production.
  • Info: meaningful normal events, such as service startup or completed background work.
  • Warn: an unexpected condition that was handled but deserves attention.
  • Error: an operation failed and could not be completed at that boundary.

Do not log routine client mistakes as server errors merely because an HTTP response uses a 4xx status.

Add shared attributes

requestLogger := logger.With(
    "request_id", requestID,
    "method", request.Method,
    "path", request.URL.Path,
)

requestLogger.Info("request completed", "status", status, "duration", duration)

Logger.With creates a logger that includes those attributes in future records.

Use LogAttrs and typed attributes in very hot paths or when explicit types improve clarity:

logger.LogAttrs(
    ctx,
    slog.LevelInfo,
    "request completed",
    slog.Int("status", status),
    slog.Duration("duration", duration),
)

Passing a context allows a handler to extract contextual information; cancelling the context does not cancel the log call.

Log an error once

Lower layers should usually add context and return an error:

return fmt.Errorf("load lesson %q: %w", id, err)

Log it at the application boundary that decides the operation has failed:

logger.Error("request failed", "error", err, "request_id", requestID)

Logging at every layer creates duplicate records for one failure.

Protect sensitive information

Do not log:

  • passwords or password hashes;
  • access tokens, API keys, or session cookies;
  • private keys;
  • full authorization headers;
  • complete request or response bodies by default;
  • personal data unless the operational need and retention policy are clear.

Use a safe identifier, classification, or redacted representation instead.

Test logging behaviour

testing/slogtest helps verify custom handlers. For application code, a small handler or buffer can capture records so a test can assert important attributes without comparing timestamps or complete formatted lines.

Prefer testing that a security-sensitive value is absent and a stable event attribute is present.

Common mistakes

  • Using dynamic sentences as event names: queries become brittle.
  • Using inconsistent keys: choose conventions such as request_id and use them everywhere.
  • Logging before redaction: changing output formatting later cannot recover a leaked secret.
  • Treating logs as control flow: return errors or values; do not require callers to parse logs.
  • Performing expensive work for disabled debug logs: use level checks when attribute construction is costly.

Practice

Write HTTP logging middleware that records method, path, status, duration, and request ID. It must not log query parameters or request bodies. Make the logger an explicit dependency.

Summary

  • Treat logs as named events with stable attributes.
  • Configure handlers and levels once at startup.
  • Add request-scoped fields with derived loggers or contextual logging methods.
  • Add error context in lower layers and log once at the final boundary.
  • Design redaction before production data reaches the logger.

Official reference: Structured Logging with slog.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026