---
title: "Logging"
description: "Logs as discrete timestamped events: structured JSON, log levels, fields to include, and what never to log."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Logging

Logs are timestamped records of discrete events: **what happened, when, and in
what context**. A payment failed. A user signed in. A background job completed with
142 rows processed. Each event stands alone and carries the context needed to
understand it: who triggered it, what the outcome was, which request it belonged to.

Where metrics show that error rate spiked at 14:32, logs show _which_ requests failed
and _why_. Where traces show that a request took 800ms, logs show the decisions made
along the way.

[OpenTelemetry](https://opentelemetry.io/) defines logs as one of the three core
observability signals alongside metrics and traces. Emit structured JSON and carry
`trace_id` and `span_id` on every line; most backends (Grafana, Datadog, Honeycomb)
will turn those IDs into direct links to the corresponding trace.

## Structured logging with `log/slog`

Go 1.21 added `log/slog` to the standard library. No dependencies, two handlers
out of the box: `TextHandler` for development, `JSONHandler` for production.

```go
// Production: one JSON object per line, parseable by any log aggregator.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))

// Development: human-readable key=value pairs.
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
```

Log a message with fields:

```go
logger.Info("server started", "addr", ":8080", "env", "production")
```

JSON output:

```json
{
  "time": "2024-01-15T10:30:00.123Z",
  "level": "INFO",
  "msg": "server started",
  "addr": ":8080",
  "env": "production"
}
```

Set the default logger once at startup so callsites can use the top-level functions
without threading a logger through every function:

```go
func main() {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    slog.SetDefault(logger)
    slog.Info("server started", "addr", ":8080")
}
```

For anything non-trivial, pass the logger explicitly rather than relying on the
global; it makes dependencies visible and tests easier to write.

## Log levels

Log levels are a filtering mechanism, not a severity decoration. Their value comes
from discipline: if INFO can mean anything, it means nothing.

| Level   | Audience   | When to use                                                            |
| ------- | ---------- | ---------------------------------------------------------------------- |
| `DEBUG` | Developers | Detailed internal state useful during local investigation              |
| `INFO`  | Operators  | Normal events an operator genuinely needs to know about                |
| `WARN`  | Operators  | Degraded but continuing: something unexpected happened and was handled |
| `ERROR` | On-call    | A request or operation failed and requires attention                   |

**DEBUG**: off in production by default. Log whatever helps you understand what
the code is doing during development or when diagnosing a specific incident with
elevated logging temporarily enabled. Never leave it permanently on in production.

```go
slog.Debug("cache miss", "key", key, "ttl", ttl)
```

**INFO**: reserve for events an operator would genuinely want to know about in a
running system: the service started, a background job completed, a significant state
transition occurred.

:::caution[The INFO bloat trap]
INFO is the most abused level. Teams log every function entry, every branch taken, every item in a
loop, and production becomes a firehose. If you can't read your INFO logs during an incident
without grepping aggressively, you have too much INFO. A useful test: would an operator on call at
3am want this line in their terminal?
:::

```go
// Good: meaningful lifecycle events
slog.Info("server started", "addr", ":8080", "version", version)
slog.Info("background job completed", "job", "invoice_sync", "processed", count)

// Bad: noise
slog.Info("entering handleRequest")
slog.Info("user found in database")
```

**WARN**: something unexpected happened but the request continued. The system is
degraded, not broken. If a WARN fires constantly under normal load, it's either
noise (remove it) or masking a real problem (make it an ERROR).

```go
slog.Warn("payment retry succeeded", "attempt", 3, "order_id", orderID)
slog.Warn("cache unavailable, falling back to database", "err", err)
```

**ERROR**: a request failed or an operation could not complete. Every ERROR should
be either investigated or triaged as expected and suppressed. An ERROR that fires
regularly and is ignored is worse than no logging at all.

```go
slog.Error("failed to process payment", "err", err, "order_id", orderID)
```

Always include the error value as `"err"`. Log at the point of failure, not at every
caller up the stack; that causes the same error to appear multiple times.

### Client errors vs. server errors

```go
func logOutcome(log *slog.Logger, status int, err error) {
    switch {
    case status >= 500:
        log.Error("request failed", "status", status, "err", err)
    case status >= 400:
        log.Warn("request rejected", "status", status, "err", err)
    default:
        log.Info("request completed", "status", status)
    }
}
```

**4xx: log at WARN.** The user sent bad data or an invalid token. Your system
behaved correctly; logging these at ERROR pollutes alerting with noise.

**5xx: log at ERROR.** Something on your side failed.

### Configuring the minimum level

```go
level := slog.LevelInfo
if os.Getenv("LOG_LEVEL") == "debug" {
    level = slog.LevelDebug
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
```

Wire the level to an environment variable so you can raise it to `DEBUG` without
redeploying.

## Fields

The fields you include determine whether a log line is useful during an incident.
The fields you exclude determine whether you stay compliant and secure.

### Always include

| Field           | Key        | Example                                                      |
| --------------- | ---------- | ------------------------------------------------------------ |
| Timestamp       | `time`     | `"2024-01-15T10:30:00.123Z"` (added automatically by `slog`) |
| Level           | `level`    | `"INFO"` (added automatically)                               |
| Message         | `msg`      | Short human description of the event                         |
| Service name    | `service`  | `"payments-api"`                                             |
| Service version | `version`  | `"1.4.2"`                                                    |
| Trace ID        | `trace_id` | Links the log line to the active OTEL trace                  |
| Span ID         | `span_id`  | Links the log line to the specific span                      |

Set `service` and `version` once as default attributes so they appear on every line:

```go
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(
    "service", "payments-api",
    "version", os.Getenv("APP_VERSION"),
)
slog.SetDefault(logger)
```

### Request context fields

For HTTP servers, attach these to every log line scoped to a request:

| Field       | Key           | Example                                          |
| ----------- | ------------- | ------------------------------------------------ |
| Request ID  | `request_id`  | UUID from `X-Request-ID` or generated at ingress |
| HTTP method | `method`      | `"POST"`                                         |
| Path        | `path`        | `"/v1/orders"`                                   |
| Status code | `status`      | `201`                                            |
| Duration    | `duration_ms` | `142`                                            |
| Client IP   | `remote_ip`   | `"203.0.113.42"`                                 |

Store the request-scoped logger in context and retrieve it in handlers:

```go
type responseWriter struct {
    http.ResponseWriter
    status int
}

func (w *responseWriter) WriteHeader(code int) {
    w.status = code
    w.ResponseWriter.WriteHeader(code)
}

type loggerKey struct{}

func withLogger(ctx context.Context, log *slog.Logger) context.Context {
    return context.WithValue(ctx, loggerKey{}, log)
}

func requestLogger(logger *slog.Logger) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            requestID := r.Header.Get("X-Request-ID")
            if requestID == "" {
                requestID = uuid.New().String()
            }

            log := logger.With(
                "request_id", requestID,
                "method",     r.Method,
                "path",       r.URL.Path,
                "remote_ip",  r.RemoteAddr,
            )

            start := time.Now()
            rw := &responseWriter{ResponseWriter: w, status: 200}
            next.ServeHTTP(rw, r.WithContext(withLogger(r.Context(), log)))

            log.Info("request completed",
                "status",      rw.status,
                "duration_ms", time.Since(start).Milliseconds(),
            )
        })
    }
}
```

:::note[Make request_id your support handle]
Tell users to include the `X-Request-ID` from the response header when contacting support. Every
log line for that request carries it: one ID, full picture.
:::

In reverse-proxy deployments, `r.RemoteAddr` is the proxy's loopback address. Use the
`X-Forwarded-For` or `X-Real-IP` header that the proxy sets to get the real client IP.
Validate that these headers are set by a trusted proxy before trusting them.

### Never log

:::danger[These fields must never appear in logs]
Logging sensitive values is easy to do accidentally, especially when logging request structs or
error messages that contain them.
:::

| Category              | Examples                                                                 |
| --------------------- | ------------------------------------------------------------------------ |
| Credentials           | Passwords, PINs, security questions                                      |
| Tokens                | Session tokens, API keys, OAuth tokens, JWTs                             |
| Payment data          | Card numbers, CVVs, bank account numbers                                 |
| Personal data         | Email addresses, phone numbers, full names, dates of birth, national IDs |
| Request bodies        | May contain any of the above; log field names or schema only             |
| Authorization headers | The full `Authorization: Bearer ...` value                               |

```go
// Dangerous: logs the full request including Authorization header
slog.Debug("inbound request", "request", r)

// Dangerous: error messages sometimes embed the input that caused them
slog.Error("failed to create user", "err", err, "input", userInput)
```

Log the minimum: IDs, non-sensitive field names, counts, durations.

### Contextual grouping with `slog.Group`

```go
slog.Info("order created",
    "order_id", order.ID,
    slog.Group("customer",
        "id",   customer.ID,
        "tier", customer.Tier,
    ),
    slog.Group("payment",
        "method",       payment.Method,
        "amount_cents", payment.AmountCents,
        "currency",     payment.Currency,
    ),
)
```

```json
{
  "msg": "order created",
  "order_id": "a1b2c3d4",
  "customer": { "id": "f47ac10b", "tier": "pro" },
  "payment": { "method": "card", "amount_cents": 4999, "currency": "USD" }
}
```

Grouping prevents field name collisions and makes the JSON easier to query in
aggregators that support nested field access.

Source: https://codex.mirio.dev/observability/logging/index.mdx
