ProgramGuru

Structured Logging

Start with Structured Logging

Learn structured logging through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of structured logging.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Go’s log/slog writes messages with levels and named attributes. Structured fields such as request IDs and counts make events easier to filter than prose-only logging.

Logs often contain timestamps, so the example decodes JSON output and prints only stable fields.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for slogAttributes make logs machine-readable.Event occursStep 1Attach attributesStep 2Slog handlerStep 3Queryable recordStep 4Attributes make logs machine-readable.
Attributes make logs machine-readable.

Tools, syntax and practical notes

See the log/slog package documentation. Emit meaningful error context but redact or omit sensitive values.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
)

func main() {
	var buf bytes.Buffer
	logger := slog.New(slog.NewJSONHandler(&buf, nil))
	logger.Info("task created", "task_id", 42)
	var entry map[string]any
	if err := json.Unmarshal(buf.Bytes(), &entry); err != nil {
		panic(err)
	}
	fmt.Println("Level:", entry["level"])
	fmt.Println("Message:", entry["msg"])
	fmt.Println("ID:", entry["task_id"])
}

Output

Level: INFO
Message: task created
ID: 42

Trace what the program does

The JSON handler writes one structured record to the buffer. Decoding allows the program to report level, message and task ID without depending on the current timestamp.

Avoid common mistakes

  • Do not log passwords, session tokens or personal data unnecessarily.
  • Use stable field names so dashboards and alerts can query the logs.

Try it yourself

Add a request_id attribute and print it after decoding the JSON log record.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What makes slog output structured?
Choose one answer. You can try again.

Answer and explanation

Named attributes alongside the message

Correct. The JSON handler writes one structured record to the buffer.

What you should remember

You have practiced Structured Logging in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Input Validation →