Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
68: Structured Logging in Go
I've spent far too many late nights staring at a terminal, running a complex grep command against a 10GB log file, trying to piece together why a specific user's payment failed. In those moments, you realize that the way you write your logs isn't just a detail—it's the difference between finding a bug in five minutes or spending five hours guessing.
The Grep Nightmare
When we first start out, the instinct is to use fmt.Printf or the basic log package to describe what's happening. It feels natural. You just write a sentence that describes the error. In a payment processing system, it usually looks something like this:
log.Printf("Payment failed for user %s, transaction %s: %v", userID, txID, err)
On the surface, this is perfectly readable for a human. But logs aren't just for humans; they're for machines. When your app is running on twenty different pods in a Kubernetes cluster, you aren't reading a text file; you're querying a system like Elasticsearch, Datadog, or CloudWatch. If you want to find every failed transaction for a specific txID, you have to write a regular expression to parse a string that might change the moment a teammate decides to rewrite "Payment failed" as "Transaction failed." It's fragile, slow, and honestly, a bit miserable.
Turning Logs into Data
This is why we move to structured logging. Since Go 1.21, we have the slog package in the standard library, which treats logs as a collection of key-value pairs rather than a single formatted string. Instead of building a sentence, you're building a record.
Here is how I would rewrite that same payment failure using slog:
import "log/slog"
slog.Error("payment failed",
"user_id", userID,
"tx_id", txID,
"error", err,
)
Now, the log isn't just a line of text; it's a structured object. If you configure slog to output JSON (which you should do in production), it looks like this:
{"time":"2023-10-27T10:00:00Z", "level":"ERROR", "msg":"payment failed", "user_id":"user_123", "tx_id":"tx_987", "error":"insufficient funds"}
This is a game-changer. I can now run a query in my logging dashboard for json.tx_id == "tx_987" and get an instant result. No regex, no guessing, and no fragility.
The Cost of Consistency
You might think, "Why bother with all those extra arguments? Just typing %s is faster." And you're right—the naive way is faster to write. Structured logging requires you to be intentional about your keys. You have to decide: is it userID, user_id, or uID? If half the team uses one and half uses the other, you're back to the Grep Nightmare.
The trade-off is a bit of extra verbosity in your code for a massive increase in observability. I usually recommend creating a "logger" that is pre-populated with context. If you're inside a function that handles a specific request, you can create a sub-logger that attaches the request_id to every single call automatically:
logger := slog.Default().With("request_id", reqID)
// Now every log call using 'logger' includes the request_id automatically
logger.Info("processing payment")
logger.Error("database timeout", "retry_count", 3)
By shifting the focus from "telling a story" to "recording data," you stop guessing what happened and start knowing. It's a mental shift from writing a diary to maintaining a database of your application's behavior.
📋 Practical Task
Refactoring the Order Processing Pipeline to Structured Logs
You have been handed a legacy OrderProcessor struct that uses fmt.Printf and the standard log package to track orders. This is making it impossible for the SRE team to track order failures in production.
Your Goal: Refactor the provided code to use the log/slog package.
- Replace all
log.Printfandfmt.Printfcalls withslog.Infoorslog.Error. - Ensure that key identifiers (like
OrderID,CustomerID, andAmount) are passed as structured key-value pairs, not embedded in the message string. - Implement a
WithOrderContextmethod that returns a*slog.Loggerpre-populated with theorder_id, so that subsequent logs in the processing pipeline don't have to repeat the ID manually.
package main
import (
"fmt"
"log"
)
type Order struct {
ID string
CustomerID string
Amount float64
}
func ProcessOrder(o Order) {
// TODO: Replace this with structured logging
log.Printf("Starting process for order %s (Customer: %s)", o.ID, o.CustomerID)
if o.Amount <= 0 {
// TODO: Replace this with structured logging
fmt.Printf("Error: Order %s has invalid amount: %f\n", o.ID, o.Amount)
return
}
log.Printf("Order %s processed successfully", o.ID)
}
func main() {
order := Order{ID: "ORD-123", CustomerID: "CUST-456", Amount: 99.99}
ProcessOrder(order)
}There are no comments for now.