Skip to main content

Logging: slog

simple log example
package main

import (
"log/slog"
)

func main() {
slog.Info("Info message")
}

# Output
# 2024/01/03 10:24:22 INFO Info message

Contextual attributes

Attributes provide additional context about the logged event.

logger.Info(
"incoming request",
"method", "GET",
"time_taken_ms", 158,
"path", "/hello/world?q=search",
"status", 200,
"user_agent", "Googlebot/2.1 (+http://www.google.com/bot.html)",
)

# Output
# {
# "time":"2023-02-24T11:52:49.554074496+01:00",
# "level":"INFO",
# "msg":"incoming request",
# "method":"GET",
# "time_taken_ms":158,
# "path":"/hello/world?q=search",
# "status":200,
# "user_agent":"Googlebot/2.1 (+http://www.google.com/bot.html)"
# }

but better way to use typed values

logger.Info(
"incoming request",
slog.String("method", "GET"),
slog.Int("time_taken_ms", 158),
slog.String("path", "/hello/world?q=search"),
slog.Int("status", 200),
slog.String(
"user_agent",
"Googlebot/2.1 (+http://www.google.com/bot.html)",
),
)

Log level

set fixes log level
func main() {
opts := &slog.HandlerOptions{
Level: slog.LevelDebug,
}
handler := slog.NewJSONHandler(os.Stdout, opts)

logger := slog.New(handler)
logger.Debug("Debug message")
logger.Info("Info message")
logger.Warn("Warning message")
logger.Error("Error message")
}
set log level from var
func main() {
ogLevel := &slog.LevelVar{} // INFO
opts := &slog.HandlerOptions{
Level: logLevel,
}

handler := slog.NewJSONHandler(os.Stdout, opts)
. . .
}

JSON logs

JSON logs
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Debug("Debug message")
logger.Info("Info message")
logger.Warn("Warning message")
logger.Error("Error message")
}

# Output
# {"time":"2023-03-15T12:59:22.227408691+01:00","level":"INFO","msg":"Info message"}
# {"time":"2023-03-15T12:59:22.227468972+01:00","level":"WARN","msg":"Warning message"}
# {"time":"2023-03-15T12:59:22.227472149+01:00","level":"ERROR","msg":"Error message"}

Default logger

Customize the default Logger
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))

slog.SetDefault(logger)

// elsewhere in the application
log.Println("Hello from old logger")
}

Structured Logging with slog
Структурированное логирование в Go с помощью Slog
Logging in Go with Slog: The Ultimate Guide