Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Write Structured JSON Logs With log/slog

Emit machine-readable JSON logs with log/slog, attach typed key-value fields, and derive request-scoped loggers. After this, your service logs are easy to filter and alert on.

Course content

Sign in to save your progress.

Course Home

fmt.Printf("user %d failed: %s\n", id, err) is fine while watching a single terminal on your laptop—and useless when 50,000 requests per minute stream into Loki, Datadog, or CloudWatch and you need to filter for status >= 500 AND path = "/orders". Plain text forces fragile regexes over log lines.

Go 1.21+ includes log/slog right in the standard library: structured key-value logging with JSON or text handlers, log levels, request-scoped child loggers via .With(...), and zero-allocation hot-path attributes.

Skip ahead

If you already configure slog.NewJSONHandler, attach request context with .With(...) and slog.Group, and keep messages static, move on to "Query Relational Data Safely With database/sql."

Experiment 1: Structured JSON logging with With and slog.Group

Look at how a base JSON logger creates a request-scoped child logger once at the start of an HTTP handler, attaching request_id and nested http metadata so every downstream log line automatically carries them:

package main

import (
	"log/slog"
	"os"
)

func main() {
	base := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
	}))
	reqLog := base.With(
		"request_id", "req-42",
		slog.Group("http", "method", "GET", "path", "/orders"),
	)
	reqLog.Info("request handled", "status", 200, "duration_ms", 12)
}
{"time":"2026-11-27T13:59:24.140521581Z","level":"INFO","msg":"request handled","request_id":"req-42","http":{"method":"GET","path":"/orders"},"status":200,"duration_ms":12}

Notice the difference from fmt.Printf: msg stays a short, static event name ("request handled"), while every variable (request_id, status, duration_ms) is a typed JSON field your log platform can index, graph, and alert on immediately.

Experiment 2: Text output in local dev vs. JSON in production

Swapping between human-friendly local logs and machine-parsed production JSON takes a single if statement at startup—none of your application code changes:

var handler slog.Handler
opts := &slog.HandlerOptions{Level: slog.LevelInfo}
if os.Getenv("APP_ENV") == "prod" {
	handler = slog.NewJSONHandler(os.Stdout, opts)
} else {
	handler = slog.NewTextHandler(os.Stdout, opts)
}
logger := slog.New(handler)
slog.SetDefault(logger)

Calling slog.SetDefault(logger) once in main() even routes legacy standard-library log.Printf(...) calls from dependencies cleanly through your JSON handler.

Experiment 3: Avoiding allocations on hot paths with LogAttrs

Ordinary calls like reqLog.Info("handled", "status", 200) pass ...any, which can box integers onto the heap. On high-throughput middleware logging thousands of requests per second, LogAttrs takes strongly typed slog.Attr values with zero boxing allocations—and catches odd-number key/value typos at compile time:

reqLog.LogAttrs(ctx, slog.LevelInfo, "request handled",
	slog.Int("status", 200),
	slog.Int64("duration_ms", 12),
)

Experiment 4: Redacting sensitive fields with slog.LogValuer

Accidental secret leaks in logs happen when someone logs a whole struct containing an API key or password. Implementing LogValue() slog.Value on sensitive types guarantees they always log as "[REDACTED]" no matter who passes them to slog:

type SecretToken string

func (SecretToken) LogValue() slog.Value {
	return slog.StringValue("[REDACTED]")
}

Common mistakes

  • Interpolating variables into the log message: Writing logger.Info(fmt.Sprintf("order %d failed", id)) creates thousands of unique messages that are impossible to group or count. Keep msg static ("order failed") and pass "order_id", id.
  • Passing an odd number of arguments to slog.Info: Produces a "!BADKEY" attribute in your JSON output; use go vet (which catches mismatched slog args) or typed slog.Attrs.
  • Logging at Debug level unconditionally in production: Flooding stdout with debug JSON under load can burn more CPU on JSON serialization than your actual business logic.

💡 Tip

Pass a slog.LevelVar as HandlerOptions.Level if you want to toggle Debug logging on and off at runtime (for example via an internal admin endpoint) without restarting your Go server.

What happens if you skip this step

During a production incident, you end up grepping unstructured multi-line print statements across 12 containers without request IDs, unable to tell which failed SQL query belonged to which HTTP 500 response.

Why is logger.Error("payment failed", "order_id", id, "err", err) far better for production monitoring than logger.Error(fmt.Sprintf("payment failed for order %d: %v", id, err))?

About

Emit machine-readable JSON logs with log/slog, attach typed key-value fields, and derive request-scoped loggers. After this, your service logs are easy to filter and alert on.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.