Slog Structured Logging JSON
Adopt Go structured logging with slog: leveled JSON handlers, grouped attributes, log record routing, and child loggers with bound context.
Code
package main
import (
"context"
"errors"
"log/slog"
"os"
)
type PaymentHandler struct {
logger *slog.Logger
}
func (h *PaymentHandler) Settle(ctx context.Context, orderID string, amount int) error {
logger := h.logger.With(
slog.String("order_id", orderID),
slog.Int("amount_cents", amount),
)
logger.InfoContext(ctx, "settlement started")
if amount > 1_000_000 {
logger.ErrorContext(ctx, "settlement rejected",
slog.String("reason", "single-charge limit"),
slog.Group("risk",
slog.Int("score", 91),
slog.String("band", "high"),
),
)
return errAmountTooHigh
}
logger.InfoContext(ctx, "settlement completed")
return nil
}
var errAmountTooHigh = errors.New("amount exceeds single-charge limit")
func main() {
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{})
logger := slog.New(handler).With(
slog.String("service", "billing"),
slog.String("region", "cn-north"),
)
payments := &PaymentHandler{logger: logger}
_ = payments.Settle(context.Background(), "ord-42", 250_000)
_ = payments.Settle(context.Background(), "ord-43", 2_500_000)
slog.SetDefault(logger)
slog.Info("default logger now carries bound context")
}What the code does
Count the functions Settle and main as the entire surface area of Slog Structured Logging JSON.
Applying it
Entry signature: func (h *PaymentHandler) Settle(ctx context.Context, orderID string, amount int) error
The entry point wires Settle together — run it once and the whole demo flows.
Statements that matter
var errAmountTooHigh = errors.New("amount exceeds single-charge limit")
_ = payments.Settle(context.Background(), "ord-43", 2_500_000)
_ = payments.Settle(context.Background(), "ord-42", 250_000)
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- How do you run Slog Structured Logging JSON?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.