These are the notes for Go episode 38. Raju's shop server runs all night. While debugging, he adds fmt.Println calls, and they end up inside the nightly CSV report that the accountant's script reads. The messages have no time and no severity. So you invent logging: messages about the program, written to standard error with a time, using Go's log package (flags, prefixes, log.New, and the important difference between log.Fatal and log.Panic). Then three developers describe the same failure three different ways and a search finds only one of them, so you invent structured logging with log/slog: a message plus named attributes, handlers for text and JSON, levels, groups, With, LogValuer to keep secrets out of logs, and a custom handler.
Every program here runs as-is in the SyntaxPilot compiler (language: Go) with go run main.go. All outputs are from real runs (Go 1.24.7, linux/amd64). The outputs below show standard output and standard error together, the way a terminal does. Lines with dates and times differ on every run.
Facts and sources
From the documentation shipped with Go 1.24.7 (go doc log, go doc log/slog, go doc os.Exit):
- The standard
loglogger "writes to standard error and prints the date and time of each logged message." "The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message." os.Exit: "The program terminates immediately; deferred functions are not run."- "A Logger can be used simultaneously from multiple goroutines."
slog.SetDefaultmakes the top-level functions likeslog.Infouse your logger, and "also updates the default logger used by the log package, so that existing applications that use log.Printf and related functions will send log records to the logger's handler".- A
LevelVar"allows the level to be varied dynamically" and "is safe to read or write" from several goroutines. log/slogwas added in Go 1.21 (the API listapi/go1.21.txtshipped with Go).go vetreports a missing value:call to slog.Info missing a final value(realgo vetoutput).
The problem: prints in the program's output
package main
import "fmt"
func main() {
// the nightly report: a CSV that the accountant's script reads
fmt.Println("id,amount")
fmt.Println("debug: checking order 41") // a debug message
fmt.Println("41,250")
fmt.Println("debug: bad amount -5 for order 42")
fmt.Println("43,90")
}
Output:
id,amount
debug: checking order 41
41,250
debug: bad amount -5 for order 42
43,90
The accountant's script reads debug: checking order 41 as an order and fails. There is no time on the lines and no way to tell a problem from information.
A program has two output streams (channels for text):
| Stream | Name | For |
|---|---|---|
| standard output | stdout, os.Stdout |
the program's real result (the report) |
| standard error | stderr, os.Stderr |
messages about the program: errors, logs |
fmt.Println writes to stdout. Logging means recording events about a running program, kept apart from its output.
The log package (the ship's logbook)
| On a ship | In Go |
|---|---|
| the cargo list: what the ship delivers | stdout: the program's output |
| the captain's logbook, a separate book | the log, on stderr |
| every entry starts with the time | log flags: date, time, file:line |
package main
import (
"fmt"
"log"
)
func main() {
// the nightly report goes to standard output
fmt.Println("id,amount")
log.Println("checking order", 41) // logs go to standard error
fmt.Println("41,250")
log.Printf("bad amount %d for order %d", -5, 42)
fmt.Println("43,90")
}
Output (one real run; the values change on every run):
id,amount
2026/11/07 16:41:02 checking order 41
41,250
2026/11/07 16:41:02 bad amount -5 for order 42
43,90
Run with stdout saved to a file (go run main.go > report.csv) and the file contains only:
id,amount
41,250
43,90
The two log lines went to stderr, each with the date and time.
Flags and prefixes
Flags choose what is printed before each message. They are bit flags (episode 5) combined with |:
| Flag | Adds |
|---|---|
log.Ldate |
2026/11/07 |
log.Ltime |
16:15:59 |
log.Lmicroseconds |
.974522 after the time |
log.Llongfile / log.Lshortfile |
/full/path/main.go:14 / main.go:14 |
log.LUTC |
times in UTC |
log.Lmsgprefix |
put the prefix right before the message, not at the line start |
log.LstdFlags |
Ldate | Ltime (the default) |
package main
import (
"log"
"os"
)
func main() {
log.SetOutput(os.Stdout) // default is standard error
log.Println("server started on port", 8080)
log.Printf("order %d: amount %d", 42, -5)
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log.Println("with file and line")
log.SetFlags(log.LstdFlags | log.Lmsgprefix)
log.SetPrefix("[shop] ")
log.Println("with a prefix")
}
Output (one real run; the values change on every run):
2026/11/07 16:41:02 server started on port 8080
2026/11/07 16:41:02 order 42: amount -5
2026/11/07 16:41:02.539709 main.go:14: with file and line
2026/11/07 16:41:02 [shop] with a prefix
SetOutput changes where the log goes (any io.Writer, episode 33), SetFlags the flags and SetPrefix a label.
log.New: separate loggers
log.New(writer, prefix, flags) makes a new *log.Logger; the package-level default logger is untouched.
package main
import (
"log"
"os"
)
func main() {
info := log.New(os.Stdout, "INFO ", 0) // flags 0: no date
errl := log.New(os.Stdout, "ERROR ", log.Lshortfile)
info.Println("order 41 placed")
errl.Println("order 42: bad amount -5")
info.Printf("%d orders today", 3)
log.Println("the default logger still writes to stderr")
}
Output (one real run; the values change on every run):
INFO order 41 placed
ERROR main.go:12: order 42: bad amount -5
INFO 3 orders today
2026/11/07 16:41:02 the default logger still writes to stderr
log.Fatal vs log.Panic
package main
import (
"fmt"
"log"
"os"
)
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
defer fmt.Println("deferred: close the database")
_, err := os.Open("menu.txt")
if err != nil {
log.Fatal("cannot start: ", err)
}
fmt.Println("menu loaded")
}
Output:
cannot start: open menu.txt: no such file or directory
exit status 1
deferred: close the database never printed: Fatal calls os.Exit(1), which ends the program immediately without running deferred calls (episode 10). The exit status (1) is the number a program returns to the operating system; 0 means success.
package main
import (
"fmt"
"log"
"os"
)
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
defer fmt.Println("deferred: close the database")
_, err := os.Open("menu.txt")
if err != nil {
log.Panic("cannot start: ", err)
}
}
Output:
cannot start: open menu.txt: no such file or directory
deferred: close the database
panic: cannot start: open menu.txt: no such file or directory
goroutine 1 [running]:
log.Panic({0xc00010cf18?, 0x8?, 0x0?})
/usr/local/go1.24.7/src/log/log.go:432 +0x5a
main.main()
/tmp/x/main.go:16 +0xd9
exit status 2
Panic logs and then panics (episode 26): the stack unwinds, deferred calls run, and a recover could catch it. An unrecovered panic exits with status 2.
log.Fatal |
log.Panic |
|
|---|---|---|
| prints the message | yes | yes |
| then | os.Exit(1) |
panic(msg) |
| deferred calls | skipped | run |
| can be recovered | no | yes |
| use | main, at startup only |
rarely |
Rule: inside functions and libraries, return an error; only main decides to stop.
The problem: free-text logs can't be searched
package main
import (
"fmt"
"strings"
)
func main() {
// three developers wrote the same kind of log line, three ways
lines := []string{
"order 42 failed: amount -5",
"Failed to place order #57 (amount=-1)",
"ERROR amount -9 invalid, order: 63",
}
for _, l := range lines { // find every failed order id?
fmt.Println(strings.Contains(l, "failed"), l)
}
}
Output:
true order 42 failed: amount -5
false Failed to place order #57 (amount=-1)
false ERROR amount -9 invalid, order: 63
Only one of three failed orders is found: a capital F, different wording, ERROR instead of "failed". Getting the order ID out is worse (order 42, #57, order: 63). Free text is written for people, not programs.
Structured logging with log/slog (the bank passbook)
A bank passbook never writes sentences: every entry has the same columns, so anyone can add up the amounts.
| At the bank | In slog |
|---|---|
| passbook columns: date, details, amount | attributes: key=value pairs |
| printed passbook or e-statement | handler: TextHandler, JSONHandler |
| routine SMS vs fraud alert | level: Debug, Info, Warn, Error |
Structured logging writes each log entry (a record) as a message plus named fields. slog ("structured log") takes a message, then alternating keys and values:
package main
import "log/slog"
func main() {
slog.Info("order placed", "id", 41, "amount", 250)
slog.Warn("order failed", "id", 42, "amount", -5)
slog.Error("payment gateway down", "retry_in", "30s")
slog.Debug("cart contents", "items", 3) // hidden by default
}
Output (one real run; the values change on every run):
2026/11/07 16:41:03 INFO order placed id=41 amount=250
2026/11/07 16:41:03 WARN order failed id=42 amount=-5
2026/11/07 16:41:03 ERROR payment gateway down retry_in=30s
The default level is Info, so Debug records are dropped. Without SetDefault, the default slog logger writes through the log package (date and time, stderr).
Handlers: text and JSON
A handler turns records into output. slog.New(handler) makes a *slog.Logger.
package main
import (
"log/slog"
"os"
)
func main() {
text := slog.New(slog.NewTextHandler(os.Stdout, nil))
text.Info("order placed", "id", 41, "city", "New Delhi")
js := slog.New(slog.NewJSONHandler(os.Stdout, nil))
js.Info("order placed", "id", 41, "city", "New Delhi")
}
Output (one real run; the values change on every run):
time=2026-11-07T16:41:03.286Z level=INFO msg="order placed" id=41 city="New Delhi"
{"time":"2026-11-07T16:41:03.286867841Z","level":"INFO","msg":"order placed","id":41,"city":"New Delhi"}
TextHandler:key=valuepairs (quotes when a value has spaces), easy for people.JSONHandler: one JSON object per line (episode 35). Log collectors, tools that gather logs from many servers and let you search them, read JSON directly: use it on servers.niloptions = defaults (level Info).
Levels and LevelVar
A level says how serious a record is. Levels are integers: LevelDebug = -4, LevelInfo = 0, LevelWarn = 4, LevelError = 8. A handler drops records below its minimum level. A LevelVar is a level you can change while the program runs.
package main
import (
"log/slog"
"os"
)
func main() {
lvl := new(slog.LevelVar) // a level you can change while running
lvl.Set(slog.LevelDebug)
opts := &slog.HandlerOptions{Level: lvl}
log := slog.New(slog.NewTextHandler(os.Stdout, opts))
log.Debug("cart contents", "items", 3)
log.Info("order placed", "id", 41)
lvl.Set(slog.LevelWarn) // busy evening: warnings and errors only
log.Info("order placed", "id", 43)
log.Warn("stock low", "item", "samosa", "left", 2)
slog.Info("levels", "debug", int(slog.LevelDebug), "warn", int(slog.LevelWarn))
}
Output (one real run; the values change on every run):
time=2026-11-07T16:41:03.437Z level=DEBUG msg="cart contents" items=3
time=2026-11-07T16:41:03.437Z level=INFO msg="order placed" id=41
time=2026-11-07T16:41:03.437Z level=WARN msg="stock low" item=samosa left=2
2026/11/07 16:41:03 INFO levels debug=-4 warn=4
Attributes, !BADKEY, groups, With and ReplaceAttr
ReplaceAttrinHandlerOptionsis called for every attribute; return a changed attribute, or an emptyslog.Attr{}to drop it. Here it drops the time to keep lines short (and the output repeatable).- Typed attributes
slog.Int,slog.String,slog.Duration,slog.Bool,slog.Anyare clearer and avoid mistakes. - A key with no value becomes
!BADKEY;go vetwarns:call to slog.Info missing a final value. slog.Groupnests attributes under a name (customer.namein text, a nested object in JSON).logger.With(...)returns a logger that adds those attributes to every record, e.g. a request ID.
package main
import (
"log/slog"
"os"
"time"
)
func main() {
drop := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{} // drop the time, to keep this demo short
}
return a
}
opts := &slog.HandlerOptions{ReplaceAttr: drop}
log := slog.New(slog.NewTextHandler(os.Stdout, opts))
log.Info("paid", slog.Int("id", 41),
slog.Duration("took", 120*time.Millisecond))
log.Info("paid", "id", 42, "amount") // a key with no value
log.Info("paid", slog.Group("customer", "name", "Asha", "city", "Pune"))
req := log.With("request_id", "r-7") // attach to every line
req.Info("cart opened")
req.Warn("coupon expired", "code", "CHAI10")
}
Output:
level=INFO msg=paid id=41 took=120ms
level=INFO msg=paid id=42 !BADKEY=amount
level=INFO msg=paid customer.name=Asha customer.city=Pune
level=INFO msg="cart opened" request_id=r-7
level=WARN msg="coupon expired" request_id=r-7 code=CHAI10
LogValuer: keep secrets out of logs
package main
import (
"log/slog"
"os"
)
type Customer struct {
Name, Phone, Password string
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
c := Customer{"Asha", "9876543210", "chai@123"}
log.Info("login", "customer", c) // log the whole struct
}
Output (one real run; the values change on every run):
{"time":"2026-11-07T16:41:03.733700957Z","level":"INFO","msg":"login","customer":{"Name":"Asha","Phone":"9876543210","Password":"chai@123"}}
The password chai@123 is now in the log, and logs are copied to many systems and read by many people: a data leak. A bank SMS shows only the last digits of your account; logs need the same. A type that implements slog.LogValuer (one method, LogValue() slog.Value) controls what is logged for it:
package main
import (
"log/slog"
"os"
)
type Customer struct {
Name, Phone, Password string
}
func (c Customer) LogValue() slog.Value { // slog.LogValuer
return slog.GroupValue(
slog.String("name", c.Name),
slog.String("phone", "******"+c.Phone[6:]),
) // the password is never logged
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}}))
c := Customer{"Asha", "9876543210", "chai@123"}
log.Info("login", "customer", c)
}
Output:
{"level":"INFO","msg":"login","customer":{"name":"Asha","phone":"******3210"}}
slog.GroupValue builds a group value from attributes. Because the type masks itself, it is safe wherever it is logged. Redaction means hiding sensitive parts of data.
Custom handlers and the default logger
slog.Handler is an interface with four methods:
| Method | Job |
|---|---|
Enabled(ctx, level) bool |
is this level wanted? (called first, to save work) |
Handle(ctx, record) error |
write one record |
WithAttrs(attrs) Handler |
a handler that adds these attributes (used by With) |
WithGroup(name) Handler |
a handler that nests later attributes in a group |
package main
import (
"context"
"fmt"
"log"
"log/slog"
"os"
)
// Shop prints "LEVEL | message | key=value ..." with no time.
type Shop struct{ min slog.Level }
func (h Shop) Enabled(_ context.Context, l slog.Level) bool {
return l >= h.min
}
func (h Shop) Handle(_ context.Context, r slog.Record) error {
line := fmt.Sprintf("%-5s | %s |", r.Level, r.Message)
r.Attrs(func(a slog.Attr) bool {
line += " " + a.Key + "=" + a.Value.String()
return true // keep going
})
_, err := fmt.Fprintln(os.Stdout, line)
return err
}
func (h Shop) WithAttrs(as []slog.Attr) slog.Handler { return h }
func (h Shop) WithGroup(name string) slog.Handler { return h }
func main() {
slog.SetDefault(slog.New(Shop{min: slog.LevelInfo}))
slog.Info("order placed", "id", 41, "amount", 250)
slog.Debug("not shown")
slog.Error("gateway down", "retry", 3)
log.Println("old log calls go through it too")
}
Output:
INFO | order placed | id=41 amount=250
ERROR | gateway down | retry=3
INFO | old log calls go through it too |
r.Attrs(func(a slog.Attr) bool {...})visits each attribute; returnfalseto stop.- Our
WithAttrs/WithGroupare simplified (they ignore their input); a real handler must keep them. slog.SetDefaultinstalls the logger forslog.Infoetc. and for thelogpackage, solog.Printlnwent through our handler too.context.Context(thectxargument) carries request-scoped values and cancellation; it comes in episode 51.
Mini project: shop server logs
A JSON logger to stdout whose level comes from the LOG_LEVEL environment variable (episode 34); a logger With the order ID per order; Warn for bad amounts, Info for good ones; a Phone type that masks itself with LogValue.
Solution
package main
import (
"log/slog"
"os"
)
type Phone string
// LogValue masks all but the last 4 digits.
func (p Phone) LogValue() slog.Value {
s := string(p)
if len(s) < 4 {
return slog.StringValue("****")
}
return slog.StringValue("******" + s[len(s)-4:])
}
type Order struct {
ID int
Phone Phone
Amount int
}
func main() {
level := slog.LevelInfo
if os.Getenv("LOG_LEVEL") == "DEBUG" {
level = slog.LevelDebug
}
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // dropped only to keep these notes stable
}
return a
},
}))
orders := []Order{{41, "9876543210", 250}, {42, "9123456780", -5}, {43, "7012345678", 90}}
for _, o := range orders {
ol := log.With("order_id", o.ID)
ol.Debug("checking", "phone", o.Phone)
if o.Amount <= 0 {
ol.Warn("bad amount", "amount", o.Amount, "phone", o.Phone)
continue
}
ol.Info("order placed", "amount", o.Amount)
}
}
Output:
{"level":"INFO","msg":"order placed","order_id":41,"amount":250}
{"level":"WARN","msg":"bad amount","order_id":42,"amount":-5,"phone":"******6780"}
{"level":"INFO","msg":"order placed","order_id":43,"amount":90}
Run with LOG_LEVEL=DEBUG go run main.go to also see the checking records.
Common mistakes (and the real messages)
| Mistake | Real message / result | Why | Fix |
|---|---|---|---|
fmt.Println for diagnostics |
debug lines inside the CSV | stdout is for output | log / slog (stderr) |
log.Fatal deep in a function |
exit status 1, defers skipped |
os.Exit(1) stops at once |
return an error |
| free-text messages | a search finds 1 of 3 | no structure | slog attributes |
slog.Info("paid", "id", 42, "amount") |
!BADKEY=amount; vet: call to slog.Info missing a final value |
key without value | pairs, or slog.Int(...) |
slog.Debug with default options |
nothing printed | default level is Info | HandlerOptions{Level: ...} |
| logging a struct with a password | "Password":"chai@123" in the log |
every field is logged | LogValue() |
TextHandler on a server |
hard for log collectors to parse | text is for people | JSONHandler |
handler WithAttrs that drops attrs |
With fields missing |
simplified handler | store and print them |
Practice
- (Homework) Build the shop server logs (solution above).
- (Homework) Add a
request_idto every line of a request. - (Homework) Mask a card number with
LogValue. - (Homework) Change the log level while the program runs.
Solution 2
package main
import (
"fmt"
"log/slog"
"os"
)
func handle(base *slog.Logger, n int) {
log := base.With("request_id", fmt.Sprintf("r-%d", n))
log.Info("request started")
log.Info("cart loaded", "items", n+1)
log.Info("request done")
}
func main() {
base := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
handle(base, 7)
handle(base, 8)
}
Output:
level=INFO msg="request started" request_id=r-7
level=INFO msg="cart loaded" request_id=r-7 items=8
level=INFO msg="request done" request_id=r-7
level=INFO msg="request started" request_id=r-8
level=INFO msg="cart loaded" request_id=r-8 items=9
level=INFO msg="request done" request_id=r-8
Solution 3
package main
import (
"log/slog"
"os"
)
type Card string
func (c Card) LogValue() slog.Value {
return slog.StringValue("XXXX-XXXX-XXXX-" + string(c[len(c)-4:]))
}
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
log.Info("payment", "card", Card("4111111111111111"), "amount", 620)
}
Output:
level=INFO msg=payment card=XXXX-XXXX-XXXX-1111 amount=620
Solution 4
package main
import (
"log/slog"
"os"
)
var level = new(slog.LevelVar) // Info by default
func main() {
h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
})
slog.SetDefault(slog.New(h))
slog.Debug("hidden: level is Info")
level.Set(slog.LevelDebug) // e.g. when an admin flips a switch
slog.Debug("now visible")
level.Set(slog.LevelError)
slog.Warn("hidden: level is Error")
slog.Error("still visible")
}
Output:
level=DEBUG msg="now visible"
level=ERROR msg="still visible"
Quick quiz
1. What does this print? (From the video.)
defer fmt.Println("bye")
log.SetOutput(os.Stdout)
log.SetFlags(0)
log.Fatal("stop")
A. stop · B. stop, then bye · C. bye, then stop · D. a panic
Answer
A. Fatal prints, then calls os.Exit(1); deferred calls are not run.
2. Which levels does a handler with Level: slog.LevelWarn print?
Answer
Warn (4) and Error (8): records at or above the minimum.
3. Where does log.Println write by default?
Answer
Standard error, with the date and time.
4. What does logger.With("request_id", "r-7") return?
Answer
A new *slog.Logger that adds request_id=r-7 to every record it writes; the original logger is unchanged.
Interview questions
- Why log to stderr and not stdout? stdout is the program's output (it may be piped or saved); diagnostics must not corrupt it.
- What's the difference between
log.Fatalandlog.Panic? Fatal exits immediately with status 1 and skips defers; Panic panics, so defers run and it can be recovered. - What is structured logging and why use it? Records with named fields instead of free text, so tools can filter, search and aggregate reliably.
- TextHandler vs JSONHandler? Text for humans and local development; JSON for production log pipelines.
- How do you add a request ID to every log line?
logger.With("request_id", id)(or a handler that reads it from the context). - How do you avoid logging secrets? Implement
LogValueron the type, or useReplaceAttrto redact keys. - How do you change the log level at run time? Give the handler a
*slog.LevelVarand callSet. - What does
slog.SetDefaultdo to thelogpackage? It routeslog.Print*through the new handler too. - Is
*log.Loggersafe for concurrent use? Yes; each logging call makes a singleWriteto the writer.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Log | a record of events in a running program | order placed id=41 |
| Logging | writing those records | log.Println(...) |
| Stream | a channel a program writes text to | stdout, stderr |
| Standard output (stdout) | the program's real output | fmt.Println |
| Standard error (stderr) | the stream for errors and logs | log.Println |
| CSV | comma-separated values, one record per line | 41,250 |
log package |
Go's simple logger | log.Printf |
| Flags (log) | what to print before each message | log.Lshortfile |
| Prefix | a label in front of each message | [shop] |
log.New |
create a separate *log.Logger |
log.New(os.Stdout, "INFO ", 0) |
SetOutput / SetFlags / SetPrefix |
configure the default logger | log.SetOutput(os.Stdout) |
log.Fatal |
print, then os.Exit(1) |
startup failures in main |
log.Panic |
print, then panic |
rare |
os.Exit |
end the program now; defers don't run | os.Exit(1) |
| Exit status | number a program returns to the OS; 0 = success | exit status 1 |
| Stack trace | the list of function calls at a panic | goroutine 1 [running] |
| Free-text log | a sentence with values inside | "order 42 failed" |
| Structured logging | message + named fields | msg="order failed" id=42 |
log/slog |
Go's structured logging package (Go 1.21) | slog.Info(...) |
| Record | one log entry: time, level, message, attributes | slog.Record |
| Attribute | a key-value pair on a record | id=41 |
slog.Attr |
Go's type for an attribute | slog.Int("id", 41) |
!BADKEY |
marks a value that had no key | !BADKEY=amount |
| Handler | turns records into output | slog.NewJSONHandler(...) |
TextHandler |
key=value output |
level=INFO msg=... |
JSONHandler |
one JSON object per record | {"level":"INFO",...} |
| Log collector | a tool that gathers and searches logs from many servers | reads JSON logs |
HandlerOptions |
handler settings: Level, ReplaceAttr, AddSource | &slog.HandlerOptions{Level: lvl} |
| Level | how serious a record is | Debug −4, Info 0, Warn 4, Error 8 |
LevelVar |
a level that can change while running | lvl.Set(slog.LevelWarn) |
ReplaceAttr |
function to change or drop attributes | drop the time |
slog.Group |
nest attributes under a name | customer.name=Asha |
With |
logger that adds attributes to every record | log.With("request_id", "r-7") |
| Request ID | an ID that ties together one request's log lines | r-7 |
LogValuer |
interface: LogValue() slog.Value |
mask a phone |
| Redaction | hiding sensitive parts of data | ******3210 |
| Data leak | secret data reaching people who shouldn't see it | passwords in logs |
slog.SetDefault |
install the default logger (slog and log) | slog.SetDefault(l) |
| Default logger | the logger used by top-level functions | slog.Info |
go vet |
Go's checker for suspicious code | missing a final value |
Summary
- Prints mix diagnostics into a program's output; logs go to stderr with a time.
log: flags (Ldate,Ltime,Lshortfile…),SetPrefix,log.Newfor separate loggers.log.Fatal= print +os.Exit(1): defers are skipped.log.Panicpanics. Libraries return errors.- Free text can't be searched:
slogwrites records with a message, a level and key=value attributes. TextHandlerfor people,JSONHandlerfor servers; levels andLevelVarfilter records.slog.Int& co.,Group,WithandReplaceAttrshape records;LogValuerkeeps secrets out.- A custom handler implements
Enabled,Handle,WithAttrs,WithGroup;slog.SetDefaultinstalls it forslogandlog.
Next episode: Reflection basics: reflect.TypeOf, reflect.ValueOf, Kind vs Type, struct fields and tags, CanSet, Elem, calling methods, the laws of reflection, and the unsafe package.