

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
click for more info
Not enough gems
Cost: 6 gems
1: Best Practices
incomplete
2: Timestamps
incomplete
3: Minimal Logging
incomplete
4: Redundant Logs
incomplete
5: One Log Per Event
incomplete
This lesson's interactive features are locked, please to keep using them
I've seen so many logs that look like this:
time=2023-10-01T12:34:57Z level=DEBUG msg="Calling getUserFromDB"
time=2023-10-01T12:34:57Z level=DEBUG msg="Entering getUserFromDB"
func handlerGetUser() error {
slog.Debug("Calling getUserFromDB")
user, err := getUserFromDB()
// ...
}
func getUserFromDB() error {
slog.Debug("Entering getUserFromDB")
// ...
}
Calling getUserFromDB and Entering getUserFromDB are completely redundant. Choose one (probably the latter because it's less error-prone) and remove the other.
A closely related, but even more prevalent anti-pattern, comes up when logging error cases:
time=2023-10-01T12:34:57Z level=ERROR msg="Failed to validate item" item_no=0 item="Baby Food" error="item Baby Food is invalid"
time=2023-10-01T12:34:57Z level=ERROR msg="Failed to validate purchase" error="item Baby Food is invalid"
These logs are nearly identical, generated from code like this:
func order(purchase Purchase) {
if err := validatePurchase(purchase); err != nil {
slog.Error("Failed to validate purchase", "error", err)
return
}
// happy path...
}
func validatePurchase(purchase Purchase) error {
for i, item := range purchase.Items {
if err := validateItem(item); err != nil {
slog.Error("Failed to validate item", "item_no", i, "item", item, "error", err)
return err
}
}
return nil
}
To be fair, they're not entirely redundant. The validatePurchase log includes contextual details that aren't available to the parent function (order()). The solution here isn't as straightforward as the previous one. We'll come back to it later, but for now, just know that we'd prefer to compress these two logs into a single entry without losing important context.
Log this redundant failure once, at the right layer.
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.