1. Useful fields in structured logs
When you are just starting out, it feels like the main thing in a log is the “human” phrase: “could not add a task”. But as soon as you have several commands, several functions, and at least one user, you discover that you are looking not for a phrase, but for an event: which operation? on which entity? how long did it take? And that is where fields win.
Imagine two situations.
The first: you have a log line.
// "task added: id=42 in 3ms"
Looks nice, but it is “just text”. The second: you have a log entry where operation=task_add, id=42, duration=3ms. Now you can:
- quickly filter only operation=task_add;
- group by operation;
- find all events for a specific id;
- build statistics for duration.
And the nicest part: you do not need to “parse by eye” or rip pieces out of a sentence with regular expressions.
In log/slog, fields are not decoration, but the main meaning of structured logging. log/slog is part of the standard library, which means it is not a “fashionable external dependency”, but the official tool of the language.
Mini dictionary of keys: operation, id, duration
For logs to really work, one simple principle matters: one meaning — one key. If today you write op, tomorrow operation, and the day after that action, then searching turns into archaeology: “what century did we log this in, and what did we call it?”
We will fix a minimal dictionary of three keys:
| Key | Type (usually) | What it means | Example value |
|---|---|---|---|
|
|
“What we did” (short operation name) | |
|
int or string | “What we did it with” (entity identifier) | |
|
|
“How long it took” (operation execution time) | |
This does not mean that there cannot be other fields. It is just that if you start with these three, your logs will already become much more useful, and later you will add fields deliberately, not “because you can”.
2. The operation field: a stable scenario name
operation is your “anchor” in logs: a short label that answers the question “what was happening at all?” A good operation helps you quickly separate “logs about adding tasks” from “logs about showing the list” without reading every message.
The practical goal of operation: so that you can gather all records for one scenario either by eye in text logs or with a filter in JSON logs.
Example: logging the “add task” operation
Let us start with the smallest example: one Info record with the operation field.
package main
import (
"log/slog"
"os"
)
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
logger.Info(
"started command",
slog.String("operation", "task_add"),
)
// Example output (approximately):
// time=... level=INFO msg="started command" operation=task_add
}
Here it is important that "started command" is a short text, and the “which command exactly” part is not baked into the string, but placed into operation.
How to choose operation values
There are several very practical rules that save you from chaos, even if you did not think about them in advance.
First, operation should be short and stable. If you generate operation dynamically (for example, "task_add_title_"+title), you will get an endless number of different values, and filtering will become meaningless.
Second, it is convenient to choose operation as a “scenario name”, not a “function name”. You will rename and split functions, but the scenario “add a task” will remain “add a task”.
Third, do not make operation a sentence. "adding new task to list" already looks like a message. operation is more like a label than text. Good options: "task_add", "task_done", "task_list".
3. The id field: linking events to an entity
As soon as you have an entity (in our case, a “task” in a todo app), you almost always need to be able to answer the question: “which task is this about?” And that is where id becomes your best friend. Even if you do not store tasks in a database, you will still have some identifier: a number, a string, a UUID.
The main idea: id is the field that links different events in logs to one and the same entity.
Example: logging id for a created task
Suppose you already got taskID := 42. Let us log it.
package main
import (
"log/slog"
"os"
)
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
taskID := 42
logger.Info(
"task created",
slog.String("operation", "task_add"),
slog.Int("id", taskID),
)
// time=... level=INFO msg="task created" operation=task_add id=42
}
Here we use slog.Int, because our id is numeric.
id as int or as string — which should you choose
Within our course and a small CLI, it is most often convenient to start with int. It is easier to parse from arguments, easier to print, easier to compare.
But sometimes id is naturally a string: for example, "a7f3c9" or a UUID. Then it is perfectly fine to do this:
logger.Info("task loaded",
slog.String("operation", "task_get"),
slog.String("id", "a7f3c9"),
)
What matters more is not the “type as in the textbook”, but the stability of the type. If today you write id as a number and tomorrow as a string, then log analysis turns into a surprise: “why are some records id=42, and others id="042"?”
Several identifiers: when you need a second key
Yes, sometimes one id is not enough. But in this lecture we are keeping minimalism: one id.
If you need more identifiers, it is better to introduce more specific keys: task_id, user_id, file_id. That is already the next level of the “field dictionary”. Here we are training discipline: at least one identifier, but always.
4. The duration field: measuring execution time
If operation answers “what did we do?”, and id answers “with what?”, then duration answers “how long?” And this field quickly becomes a favorite, because it catches performance regressions before someone has time to write an angry issue saying “your app is slow”.
In Go, measuring duration is usually done with start := time.Now() and then time.Since(start). A nice nuance: time in Go can account for monotonic clocks, so time.Since(start) works correctly even if the system “wall clock” jumped.
Example: duration as a field
package main
import (
"log/slog"
"os"
"time"
)
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
start := time.Now()
time.Sleep(10 * time.Millisecond)
logger.Info(
"operation finished",
slog.String("operation", "demo_sleep"),
slog.Duration("duration", time.Since(start)),
)
// time=... level=INFO msg="operation finished" operation=demo_sleep duration=10ms
}
Pay attention: we do not write “finished in 10ms” in the text. We put the duration into the duration field. The text stays stable.
Micro-pattern: helper for duration
To avoid writing time.Since(start) everywhere by hand, it is convenient to define a small helper that returns a slog.Attr. Then the logging code becomes “cleaner to the eye”.
package main
import (
"log/slog"
"time"
)
func durationAttr(start time.Time) slog.Attr {
return slog.Duration("duration", time.Since(start))
}
This helper is small, but it enforces discipline: you always name the field the same way (duration), and you always put exactly time.Duration there.
5. Embedding operation/id/duration into a todo CLI application
Now let us put everything together in pieces that look like real CLI code. We will not build a complex architecture (that is a separate topic), but we will do enough for you to feel: “aha, this is where these fields actually live.”
The scenario is this: the add command creates a task and logs an event with operation, id, duration.
Model and simple in-memory storage
Let us start with a tiny storage that issues an auto-incrementing ID.
package main
import "time"
type Task struct {
ID int
Title string
CreatedAt time.Time
}
type TaskStore struct {
nextID int
tasks []Task
}
func (s *TaskStore) Add(title string) Task {
s.nextID++
t := Task{ID: s.nextID, Title: title, CreatedAt: time.Now()}
s.tasks = append(s.tasks, t)
return t
}
The code is deliberately simple: no files, no databases, no magic. Right now we care about logs, not about permanent task storage (otherwise we would accidentally give a lecture on persistence, and that is already a different series).
Setting up slog and a basic logger
Let us assemble a logger that writes to stderr so it does not interfere with the command result.
package main
import (
"log/slog"
"os"
)
func newLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(os.Stderr, nil))
}
Yes, that is “two lines”. And yes, that is how it should be: a good logger is not necessarily “100 lines of configuration”, especially in a teaching CLI.
The add command: logging operation, id, duration
Now for the best part: we wrap command execution in time measurement and write a structured log.
package main
import (
"fmt"
"log/slog"
"time"
)
func runAdd(logger *slog.Logger, store *TaskStore, title string) {
start := time.Now()
task := store.Add(title)
// stdout: command result contract
fmt.Printf("%d\n", task.ID) // for example: 1
// stderr: diagnostics (logs)
logger.Info(
"task added",
slog.String("operation", "task_add"),
slog.Int("id", task.ID),
slog.Duration("duration", time.Since(start)),
)
}
Here the division of responsibilities is very visible: fmt.Printf prints the “result” (the task ID), while logger.Info prints “what happened inside”.
Mini-main: tying everything together in one program
Let us make a very simple main that expects add <title>. We do not use flag because that belongs to separate lectures about CLI design, and our task here is log fields.
package main
import (
"fmt"
"os"
)
func main() {
logger := newLogger()
store := &TaskStore{}
if len(os.Args) < 3 || os.Args[1] != "add" {
fmt.Fprintln(os.Stderr, "usage: todo add <title>")
return
}
title := os.Args[2]
runAdd(logger, store, title)
}
In a real program, you would also handle errors, support more commands, store tasks between runs, and so on. But even on this “skeleton”, it is already clear: operation, id, duration fit into the code naturally.
A small diagram: what we did
Sometimes it is useful to see this as a flow of events: where we measure time and where we write fields.
flowchart TD
A["User: todo add 'milk'"] --> B["runAdd: start := time.Now()"]
B --> C["store.Add -> Task{ID}"]
C --> D[stdout: print ID]
D --> E[stderr: logger.Info with operation/id/duration]
E --> F[End]
If you have ever chased a bug like “why did my stdout output break?”, then such a diagram helps quickly: you literally see where the boundary between “result contract” and “diagnostics” runs.
6. Common mistakes when working with operation, id, duration
Mistake #1: operation changes every time and turns into an endless zoo.
It is very tempting to make operation “beautiful” and include details in it: user name, task title, filter parameters. In the end you get thousands of unique operation values, and filtering by them loses its meaning. operation should be short, from a small fixed set, and details should go into separate fields.
Mistake #2: id is sometimes a number and sometimes a string, and nobody understands how to search.
Today you log id as 42, tomorrow as "42", and the day after tomorrow as "042". The eye may survive that somehow, but automated log analysis will start to get sad. Choose a type and format and keep it stable: if your id is int, log it as slog.Int("id", id) everywhere.
Mistake #3: duration is hidden inside the message text, and the field is called sometimes t, sometimes elapsed, sometimes time_ms.
When duration lives inside a string, you cannot properly aggregate and compare times. When the key is named differently, you cannot reliably filter and build statistics. Make duration a separate field and name it the same way every time: duration.
Mistake #4: measuring duration “randomly” and getting strange numbers.
A common bug is to put start := time.Now() too late (after half the work has already happened) or too early (before parsing arguments, although you wanted to measure only storage work). There is no single right answer here, but there is a rule: measure what you really want to compare. And yes, time.Since(start) in Go is a normal basic method; it accounts for monotonic time.
Mistake #5: mixing stdout and logs, and then wondering why tests and scripts broke.
If you print the “task ID” to stdout and also throw “DEBUG: task added…” there, then any user script that expected one number suddenly gets a mess. Keep the discipline: command results go to stdout, logs go to stderr.
GO TO FULL VERSION