

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Structured Logging
incomplete
2: Slog Package
incomplete
3: Log Levels
incomplete
4: More Log Levels
incomplete
5: Key-Value Pairs
incomplete
6: Output Formats
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
In Go 1.21 (June 2023), the log/slog package was added to the standard library to support structured logging. There was much rejoicing.
There are several third-party logging libraries, like:
Most predate log/slog, and unless you have very specific needs, log/slog is probably all you need these days. Compare a standard log message:
2023/10/01 12:00:00 This is a log message
To a structured log/slog message:
2024-01-15T10:30:45.123Z INFO msg="user login successful" user_id=12345 username=john_doe ip_address=192.168.1.100 duration_ms=245
The log/slog package introduces handlers, which accept arbitrary key-value pairs and format them into a log record. Two built-in handlers are:
log/slog.NewTextHandler: Formats logs as plain textlog/slog.NewJSONHandler: Formats logs as JSON.The log/slog.New function takes a handler as an argument, and returns a logger instance that can be used to log messages:
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
Then we can use it like this:
logger.Info("This is an info message")
The structured logger doesn't support formatting methods like Infof, so use fmt.Sprintf when needed:
logger.Info(fmt.Sprintf("Failed to open file %s: %s", filename, err))
Switch Linko to structured logging with slog.
Use fmt.Sprintf to format strings as needed. slog doesn't have Infof or similar methods.
Restart your server:
go run .
Run and submit the CLI tests from the root of the Linko repo.