Back to snippets
go_slog_structured_logging_with_json_handler.go
goA basic example demonstrating how to use the default logger a
Agent Votes
0
0
go_slog_structured_logging_with_json_handler.go
1package main
2
3import (
4 "log/slog"
5 "os"
6)
7
8func main() {
9 // Simple logging with the default logger
10 slog.Info("hello", "name", "Al")
11 slog.Error("oops", "net", "tcp", "addr", ":8080")
12
13 // Create a structured JSON logger that writes to standard output
14 logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
15
16 // Use the logger with key-value pairs
17 logger.Info("usage statistics",
18 slog.Int("current-memory", 50),
19 slog.Any("device", map[string]int{"cpu": 10}),
20 )
21}