The Real-World Problem: When Plain-Text Logs Torment Developers at Midnight
In the early days of writing Go, a common habit for many developers was scattering log.Printf("user %d failed to login, err: %v", userID, err) throughout the codebase. On a local machine with a few dozen test runs, this works just fine. Everything falls apart, however, once the service hits production and handles 2,000 to 5,000 requests per second.
Your terminal gets flooded with millions of rapid text lines scrolling past. When an incident occurs at 2 AM, running grep or using awk to sift through multi-gigabyte log files quickly becomes overwhelming. Centralized monitoring platforms like Elasticsearch, Loki, or Datadog cannot parse individual fields for automated alerting because plain-text strings lack a consistent format.
Before Go 1.21, we had to rely on third-party libraries like uber-go/zap or rs/zerolog. While excellent, different teams often picked different packages, fragmenting projects across an organization. Starting with Go 1.21 in August 2023, the log/slog package officially joined the Standard Library. You now get high-performance, zero-dependency, and consistent structured logging out of the box.
Understanding Structured Logging and the Architecture of slog
Structured logging replaces free-form text strings with standardized key-value pairs, typically formatted as JSON. Machines can easily parse JSON, index specific fields, and execute queries in just a few milliseconds.
The Three Building Blocks: Record, Handler, and Logger
The architecture of log/slog revolves around three distinct components:
- Record: The raw log unit containing a timestamp, log level (INFO, ERROR, etc.), main message, and a list of attributes.
- Handler: The processing engine that consumes a Record, formats it, and dispatches it to a destination (stdout, file, socket). Go provides built-in
TextHandlerfor local development andJSONHandlerfor production. - Logger: The developer-facing frontend providing familiar logging methods such as
Debug(),Info(),Warn(), andError().
Step-by-Step Guide: Mastering slog in a Go Project
Step 1: Initializing a Basic Logger with JSONHandler
To get started, import log/slog and os. The snippet below initializes a JSON logger writing directly to standard output:
package main
import (
"log/slog"
"os"
)
func main() {
// Initialize JSON Handler writing to stdout
handler := slog.NewJSONHandler(os.Stdout, nil)
logger := slog.New(handler)
// Log directly with key-value pairs
logger.Info("user logged in successfully",
"user_id", 1024,
"role", "admin",
"ip_address", "192.168.1.15",
)
}
Running the application outputs a clean, single-line JSON log:
{"time":"2026-11-28T10:00:00.123456789Z","level":"INFO","msg":"user logged in successfully","user_id":1024,"role":"admin","ip_address":"192.168.1.15"}
When reading long JSON log lines printed to the console, single-line compressed text can be hard to inspect. You can paste them into online tools like toolcraft.app (specifically: toolcraft.app/tools/developer/json-formatter) to format them into a clean tree view without installing bulky extensions.
Step 2: Configuring Log Levels and Enabling Code Source Location (AddSource)
By default, slog ignores DEBUG logs and only outputs INFO and above. During development, you often want more granularity. Use slog.LevelVar to change log levels dynamically at runtime without restarting your container:
package main
import (
"log/slog"
"os"
)
func main() {
// LevelVar allows dynamic level updates via an internal API if needed
programLevel := new(slog.LevelVar)
programLevel.Set(slog.LevelDebug)
opts := &slog.HandlerOptions{
Level: programLevel,
AddSource: true, // Output file name and line number of the log call
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
slog.SetDefault(logger) // Replace the application-wide default logger
slog.Debug("database connected successfully", "db_host", "localhost", "port", 5432)
slog.Error("failed to query data", "error", "record not found")
}
The generated source field points directly to main.go:21, saving considerable time tracking down function execution when unexpected errors occur.
Step 3: Grouping Attributes and Creating Child Loggers
In large-scale systems, multiple services aggregate logs into a single collector. Without proper namespacing, an order’s id field can clash or get confused with a user’s id. Slog solves this cleanly using slog.Group and the With() method:
package main
import (
"log/slog"
"os"
)
func main() {
baseLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Create child logger with pre-attached billing module context
billingLogger := baseLogger.With(
slog.String("service", "billing-service"),
slog.String("env", "production"),
)
// Group customer details into a sub-object
billingLogger.Info("processing order payment",
slog.String("order_id", "ORD-9988"),
slog.Float64("amount", 150000.0),
slog.Group("customer",
slog.Int("id", 42),
slog.String("email", "[email protected]"),
),
)
}
The output JSON nests the customer group cleanly into a sub-object:
{
"time": "2026-11-28T10:05:00Z",
"level": "INFO",
"msg": "processing order payment",
"service": "billing-service",
"env": "production",
"order_id": "ORD-9988",
"amount": 150000,
"customer": {
"id": 42,
"email": "[email protected]"
}
}
Step 4: Wrapping a Custom Handler to Automatically Attach Request IDs from Context
In microservices architectures, every request requires a request_id (correlation ID) to trace execution across various service layers. Forcing developers to manually append "request_id", reqID to every single log statement is error-prone and unsustainable.
The idiomatic approach is wrapping slog.Handler in a custom handler to automatically extract values from context.Context:
package main
import (
"context"
"log/slog"
"net/http"
"os"
)
type contextKey string
const requestIDKey contextKey = "request_id"
// ContextHandler wraps the base Handler to automatically extract keys from ctx
type ContextHandler struct {
slog.Handler
}
func (h *ContextHandler) Handle(ctx context.Context, r slog.Record) error {
if reqID, ok := ctx.Value(requestIDKey).(string); ok {
r.AddAttrs(slog.String("request_id", reqID))
}
return h.Handler.Handle(ctx, r)
}
func main() {
jsonHandler := slog.NewJSONHandler(os.Stdout, nil)
customLogger := slog.New(&ContextHandler{Handler: jsonHandler})
slog.SetDefault(customLogger)
http.HandleFunc("/api/order", func(w http.ResponseWriter, r *http.Request) {
reqID := r.Header.Get("X-Request-ID")
if reqID == "" {
reqID = "req-8899-xyz"
}
// Attach request ID to context
ctx := context.WithValue(r.Context(), requestIDKey, reqID)
// Log using InfoContext - request_id is automatically injected into the output
slog.InfoContext(ctx, "starting inventory check")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"success"}`))
})
slog.Info("server is running on port :8080")
http.ListenAndServe(":8080", nil)
}
The resulting log consistently includes "request_id":"req-8899-xyz". Even when a request flows five levels deep from business service to database repository, simply pass ctx along and call slog.InfoContext(ctx, ...).
Best Practices for Optimizing slog in Production
Running slog in high-throughput production environments benefits from a few practical optimizations for speed and data security:
- Use Strongly Typed Attributes: On high-throughput endpoints handling tens of thousands of requests per second, avoid loose key-value pairs like
"count", 10(which triggers Go interface heap allocations). Instead, useslog.Int("count", 10)orslog.String(...)to eliminate unnecessary allocations. - Control Log Levels via Environment Variables: Read
os.Getenv("LOG_LEVEL")during application startup to configure yourLevelVar. This allows seamless switching from INFO to DEBUG when diagnosing issues in staging or production. - Mask Sensitive Data with
slog.LogValuer: Never log plaintext tokens, passwords, or credit card numbers. Have your data structs implement theLogValue() slog.Valueinterface to automatically return"***REDACTED***"before writing to the log stream.

