Skip to Content
Skip to content
Replace fmt.Println With Structured JSON Logging in Go (log/slog)
Intermediate
Tutorials

Replace fmt.Println With Structured JSON Logging in Go (log/slog)

Switch from fmt.Println to log/slog JSON logs, attach request-scoped attributes with With, redact secrets using LogValuer, and change log levels at runtime. After this, your Go logs are filterable and leak-safe.

Updated 4 min read GoTesting and Debugging

fmt.Printf("order %d failed for user %s: %v\n", id, user, err) is readable when one developer watches a terminal—and miserable in production when 50,000 log lines per minute stream into Datadog, Loki, or CloudWatch and you need to filter for status >= 500 AND path = "/orders".

Go 1.21+ includes log/slog directly in the standard library: structured JSON/text handlers, log levels, child loggers via .With(...), and zero-allocation hot-path attributes. Verified on Go 1.27.

Case 1: JSON in production vs. readable text in local dev

Configure one handler at startup in main() based on the environment, and register it with slog.SetDefault(logger) so even legacy log.Printf calls from third-party libraries emit clean structured JSON:

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

Case 2: Request-scoped loggers with .With and slog.Group

Attach per-request fields (like request_id and nested HTTP metadata) once using .With(...) so every downstream log line automatically carries them without repeating the same arguments:

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 golden rule of structured logging: keep msg a short, constant event name ("request handled") and put all dynamic values into typed key-value attributes so log dashboards can group, filter, and alert cleanly.

Case 3: Zero-allocation hot-path logging with LogAttrs

Ordinary logger.Info("msg", "status", 200) passes ...any, which boxes integers onto the heap. On high-throughput HTTP middleware, use strongly typed slog.Attr values with LogAttrs—zero boxing allocations, and odd-number key/value bugs become compile errors:

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

Case 4: Preventing accidental secret leaks with slog.LogValuer

If a struct contains an API token or password, implement LogValue() slog.Value on that sensitive type so slog automatically redacts it even if someone logs the entire struct:

type SecretToken string

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

💡 Tip

Pass a *slog.LevelVar as HandlerOptions.Level if you want to flip a live production server from Info to Debug temporarily via an admin endpoint without restarting it.

Common mistakes

  • Formatting variables into msg with fmt.Sprintf: Writing logger.Error(fmt.Sprintf("user %d failed", id)) destroys log grouping and forces regex parsing; pass "user_id", id as an attribute instead.
  • Passing an odd number of arguments to slog.Info: Emits "!BADKEY" in JSON; run go vet ./... (which flags bad slog pairs) or use LogAttrs.
  • Logging full request bodies or Authorization headers: Leaks passwords, JWTs, and PII into third-party log storage.

⚠ Warning

Do not log errors at every layer of the call stack (repository + service + handler)—that creates three duplicate JSON error entries for a single failure. Wrap and return errors upward, and log once at the top-level handler with the full context.

What happens if you skip this

During a 2:00 AM incident across 10 containers, unstructured fmt.Println text forces slow manual grepping without request IDs, status codes, or latency fields.

Related course: Go Intermediate.

About

Switch from fmt.Println to log/slog JSON logs, attach request-scoped attributes with With, redact secrets using LogValuer, and change log levels at runtime. After this, your Go logs are filterable and leak-safe.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.