Go by Example

Logging

Use log/slog handlers and structured fields; configure JSON or text output, levels, and sensitive-data handling.

log/slog is Go's standard structured logging package. Structured fields keep values separate from messages so log tools can search them reliably.

Create a JSON handler when the log collector expects JSON. Add fields as key-value pairs; a child logger can carry fields shared by its messages.

package main
 
import (
    "log/slog"
    "os"
)
 
func main() {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    logger.With("request_id", "abc-123").
        Info("request complete", "status", 200)
}

In production

Choose the output format and minimum level to match the deployment's log pipeline. Attach request-scoped identifiers where available, and never log passwords, tokens, or other secrets. Set HandlerOptions.Level to filter debug output. The default slog handler writes human-readable text to stderr.

Enjoyed this? Get more software craft delivered to your inbox.