

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
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
Okay, time to finally put the structure in structured logging!
Some logs, like startup and shutdown messages, don't need additional metadata... but some do. Common examples in web services are:
HTTP response code
Size of request/response bodies
Duration of the request
User ID making the request
Stack traces in the event of failure
All we need to do is add key-value pairs to the log line, for example:
logger.Info("Someone is loose in the server room",
slog.String("name", "Boots"),
slog.Int("id", 80045),
)
// 2024-01-15T10:30:45.123Z INFO msg="Someone is loose in the server room" name=Boots id=80045You can use type-specific helpers like slog.String and slog.Int, or log values directly. Both are valid, but helpers can be more consistent, and sometimes more performant:
logger.Info("Someone is loose in the server room",
"name", "Boots",
"id", 80045,
)
// 2024-01-15T10:30:45.123Z INFO msg="Someone is loose in the server room" name=Boots id=80045Structured logs are more readable, but more importantly, their interface can output JSON (or another format) just by changing the handler. Imagine if your app had thousands of log lines and you had to rewrite all of them just to ship a new format or destination... no fun.
Add structured fields to your most important logs.
Message: "Served request"
method: HTTP method of the request
path: URL path of the request
client_ip: Remote IP address of the request
Restart your server with LINKO_LOG_FILE=linko.access.log set:
LINKO_LOG_FILE=linko.access.log go run .Run and submit the CLI tests from the root of the Linko repo.