CLI Flags, Subcommands, Environment Variables & Logging (log/slog)
"Apps sometimes store config as constants in the code. This is a violation of twelve-factor, which requires strict separation of config from code. Config varies substantially across deploys, code does not." — The Twelve-Factor App, III. Config
Summary: A Go program talks to its operator through four channels: arguments (flags and subcommands), the environment, standard streams with an exit code, and logs; this chapter builds each channel on the standard library and says when cobra or zap is worth the dependency. Focus: flag (types, FlagSet, flag.Value, usage, -h), subcommands, os.Getenv/os.LookupEnv, precedence flags over env over file, exit codes and os.Exit, stdout versus stderr, log versus log/slog (handlers, levels, attributes, groups, ReplaceAttr, custom handlers), redaction, sampling, correlation ids, TTY detection, testing a CLI with testscript, and shipping with go install and GoReleaser. Learning goal: Write a command line program whose output can be piped, whose configuration can be audited, whose exit code means something, and whose logs a machine can query, then test all of it without starting a process by hand.
This page owns the mechanics of a command line program and of log/slog. It does not re-teach neighbours: how processes receive signals and shut down is in OS Processes, Signals & Graceful Shutdown; how context carries values and deadlines is in context; how errors are wrapped before they reach main is in Errors, Wrapping, Panic, Recover & Defer; readers and writers (os.Stdin, os.Stdout) are in The io Package; the go build/go install machinery is in Toolchain, Modules & Packages; HTTP request-logging middleware is in Middlewares; and what to do with logs at fleet scale (metrics, traces, retention) is in Observability: Logs, Metrics & Traces. All the code below lives in one tested module under docs/snippets/go/cli-flags-env-logging/go.
Page map
| If you are looking for | Go to |
|---|---|
| A one-minute table of the whole chapter | Everything in one minute |
| Why a CLI has more than one input and output | Why it exists |
History: flag, 12-factor, log/slog | Where it comes from |
flag.Parse, flag.Args, types, -h, -- | The flag package |
Custom flag.Value, TextVar, flag.Func | Custom flag types |
FlagSet per subcommand, os.Args[1] | Subcommands |
| cobra, urfave/cli, kong compared | CLI frameworks |
os.Getenv, os.LookupEnv, os.Environ, .env | Environment variables |
| flags over env over file | Configuration precedence |
os.Exit, exit codes, log.Fatal | Exit codes |
| stdout for data, stderr for logs, stdin | Standard streams |
log package and its limits | The log package |
| Logger, Handler, levels, attributes, groups | log/slog basics |
slog.With, LogAttrs, context, SetDefault | Loggers in practice |
ReplaceAttr, redaction, custom handlers, trace id | Handlers you write |
| keys, PII, sampling, correlation ids | Structured logging practice |
| libraries versus applications | Logging in libraries |
| zap and zerolog | Third-party loggers |
-v, --json, TTY, x/term, NO_COLOR | Verbosity, JSON and TTY |
testscript, capturing stdout | Testing a CLI |
go install, -ldflags -X, GoReleaser | Shipping a CLI |
| Exact error texts and level numbers | Mechanics |
| Fixes for classic mistakes | Solving the classic problems |
| Which tool for which job | Choosing |
| Artisan, Symfony Console, Monolog | For PHP/Laravel developers |
| From one binary to a fleet | In architecture |
| Run it yourself | Lab |
Everything in one minute
| Channel | Standard-library tool | What to remember |
|---|---|---|
| Arguments | flag | -x, --x, -x=v; stops at the first non-flag; -- ends flags |
| Subcommands | one flag.FlagSet per command, switch on os.Args[1] | Parse args[1:] with the command's own set |
| Environment | os.LookupEnv | Unset and empty are different; os.Getenv hides the difference |
| Precedence | defaults, then file, then env, then flags | Feed each layer in as the default of the next |
| Exit status | os.Exit(code) once, in main | 0 success, 1 failure, 2 usage error; deferred calls do not run |
| Data | os.Stdout | Only results; safe to pipe |
| Diagnostics | os.Stderr | Logs, progress, errors, usage text |
| Logging | log/slog since Go 1.21 | Levels, attributes, groups, handlers; one logger injected, not global |
| Secrets | slog.LogValuer, ReplaceAttr | Redact in the logger, not at each call site |
| Tests | Run(args, env, stdout, stderr) int and testscript | Make main a one-liner |
| Level | Number | Meaning | Default handler |
|---|---|---|---|
slog.LevelDebug | -4 | developer detail | hidden |
slog.LevelInfo | 0 | normal events | shown (default threshold) |
slog.LevelWarn | 4 | recoverable surprise | shown |
slog.LevelError | 8 | operation failed | shown |
| Handler | Output | When |
|---|---|---|
slog.NewTextHandler | time=... level=INFO msg=... k=v | terminals, local development |
slog.NewJSONHandler | one JSON object per line | log pipelines, containers |
slog.DiscardHandler (Go 1.24) | nothing | library default, tests |
custom slog.Handler | anything | redaction, sampling, trace ids, forwarding |
Why it exists
A program started from a shell is not a function you call with typed arguments. It has a contract with its environment that is older than Go: argv, environment variables, three file descriptors and an exit status. Every automation (shell scripts, CI jobs, Kubernetes command:, cron, systemd) speaks only that contract. If your program mixes results and logs on one stream, returns 0 after a failure, or reads a password from a flag, every caller downstream breaks quietly.
Logging exists because a running service cannot be single-stepped. A log line is the only trace of what happened, and an unstructured sentence ("user ada failed login from 203.0.113.9") cannot be filtered without a regular expression that breaks the day someone rewords it. Structured logging keeps the sentence and the facts separate.
| Trade-off | Simpler | Richer |
|---|---|---|
| Flag parsing | flag from the standard library: no dependency, tiny binary | cobra/kong: nested commands, completion, generated docs |
| Configuration | flags and env only | file layer, hot reload, remote sources (viper, koanf) |
| Logging | log.Printf: one string | log/slog: record with level, time, attributes, pluggable handler |
| Logger | package-level global | injected *slog.Logger: testable, per-request attributes |
| Output | text for humans | --json for machines, chosen by a flag or by TTY detection |
Everyday picture: a restaurant kitchen. Orders arrive on a ticket (arguments), the pantry holds standing supplies (environment), finished dishes go through the pass to the diner (stdout), the kitchen's shouted warnings stay in the kitchen (stderr), and the chef rings a bell once at the end that means "service done" or "service failed" (exit code). Nobody wants the warnings plated with the food.
Three common misunderstandings, up front
- "
os.Getenvreturns an error when a variable is missing." It returns the empty string, the same as a variable that is set to nothing. Onlyos.LookupEnvtells them apart. - "
log.Fatalis a convenient way to exit with an error." It writes and callsos.Exit(1)immediately: deferred functions do not run, files are not flushed, and no caller can recover. - "Structured logging means JSON." JSON is one encoding. Structured means the message and the attributes are separate values until the handler formats them;
TextHandleris structured too.
Where it comes from
- Unix argv/environ/streams. The contract predates Go by decades; Go exposes it as
os.Args,os.Environandos.Stdin/Stdout/Stderr. Theflagpackage has been in the standard library since Go 1.0 and deliberately keeps a single-dash, Go-flavoured syntax (it also accepts two dashes). - The Twelve-Factor App (Adam Wiggins), factor III: store configuration in the environment, strictly separate from code. It is why env vars are the default configuration channel of containers.
log(Go 1.0) gives a mutex-protected writer with a prefix and timestamp flags. It has no levels and no fields.log/slogarrived in Go 1.21 (August 2023). The Go blog post by Jonathan Amsterdam says the standard library can "provide a common framework that all the other structured logging packages can share"; the post is the design rationale (Structured Logging with slog). Go 1.24 addedslog.DiscardHandler; Go 1.25 addedslog.GroupAttrsandRecord.Source.testscriptgrew out of the script tests of the Go command itself (its documentation still says to run one withgo test cmd/go -run=TestName/^foo$) and is packaged ingithub.com/rogpeppe/go-internal/testscript.
Sources read for this page are listed in References; the opening quote is from 12factor.net/config, and the slog rationale from the Go blog post above.
The concept catalogue
The flag package Must-know
In plain words: flag turns -addr :9000 -v into typed Go variables and leaves whatever it did not consume in flag.Args().
Common misunderstanding: "flag.Parse() on the global command line is fine for any program." It works for a throwaway main, but the global flag.CommandLine uses ExitOnError: a typo calls os.Exit(2) from inside the library, so you can neither test it nor print your own message. Use your own flag.NewFlagSet(name, flag.ContinueOnError) and pass args in.
Definition: a flag is a named, typed value with a default and a usage string. flag.String, Int, Bool, Duration, Float64, Uint, Int64, Uint64 return a pointer; the ...Var forms write into a variable you own. Parse consumes arguments up to the first non-flag argument (or --) and Args() returns the rest. Accepted spellings: -flag, --flag, -flag=value, --flag=value, and -flag value for non-boolean flags. A boolean flag takes a value only in the = form: -v=false.
1 $ demo -tag a --tag=b -timeout 250ms in.txt -workers 9
2 Parse: -tag a -> Tags=[a]
3 Parse: --tag=b -> Tags=[a b]
4 Parse: -timeout 250ms -> Timeout=250ms
5 Parse: in.txt -> first non-flag argument: parsing STOPS
6 Args() = [in.txt -workers 9] (-workers stays positional, default 4)Real scenarios: a batch tool (-input, -workers, -dry-run); a one-off migration runner; a health-check binary that a Dockerfile HEALTHCHECK calls; a code generator invoked from go:generate.
| Constructor | Go type | Parse failure text (from the test) |
|---|---|---|
fs.String / StringVar | string | never fails |
fs.Int / IntVar | int | invalid value "x" for flag -workers: parse error |
fs.Bool / BoolVar | bool | invalid boolean value "maybe" for -v: parse error |
fs.Duration / DurationVar | time.Duration | invalid value "soon" for flag -timeout: parse error |
fs.Float64, Uint, Int64, Uint64 | numeric | same shape as Int |
fs.Var(value, ...) | any flag.Value | whatever Set returns |
fs.TextVar(p, ...) (Go 1.19) | encoding.TextUnmarshaler | UnmarshalText error, wrapped |
fs.Func(name, usage, fn) (Go 1.16) | callback per occurrence | the callback's error |
fs.BoolFunc (Go 1.21) | callback, no value | the callback's error |
Usage: -h and -help print the defaults and make Parse return flag.ErrHelp (text flag: help requested). Under ExitOnError that means exit status 0 for -h and 2 for any other error; under ContinueOnError you decide. The usage text goes to fs.Output(), which is stderr by default. Customise it with fs.Usage; put a name in backticks in the usage string (`address`) and PrintDefaults uses it as the placeholder instead of the type name.
// Package flagset shows the standard flag package used the careful way:
// a private FlagSet, ContinueOnError, a custom flag.Value and flag.TextVar.
package flagset
import (
"errors"
"flag"
"fmt"
"io"
"log/slog"
"strings"
"time"
)
// ListFlag is a repeatable flag: -tag a -tag b. It implements flag.Value.
type ListFlag []string
// String must tolerate a zero (nil) receiver: the flag package calls it
// on a zero value to decide whether the default is worth printing.
func (l *ListFlag) String() string {
if l == nil {
return ""
}
return strings.Join(*l, ",")
}
// Set is called once per occurrence of the flag.
func (l *ListFlag) Set(v string) error {
if strings.TrimSpace(v) == "" {
return errors.New("empty value")
}
*l = append(*l, v)
return nil
}
// Options is everything the demo program accepts.
type Options struct {
Addr string
Timeout time.Duration
Workers int
Verbose bool
Tags ListFlag
Level slog.Level
}
// Parse parses args (without the program name). It never exits and never
// writes to os.Stderr directly, so tests can call it.
func Parse(args []string, stderr io.Writer) (Options, []string, error) {
var o Options
fs := flag.NewFlagSet("demo", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.StringVar(&o.Addr, "addr", ":8080", "listen `address`")
fs.DurationVar(&o.Timeout, "timeout", 5*time.Second, "request timeout (e.g. 250ms, 5s)")
fs.IntVar(&o.Workers, "workers", 4, "number of `workers`")
fs.BoolVar(&o.Verbose, "v", false, "verbose output")
fs.Var(&o.Tags, "tag", "tag to attach (repeatable)")
fs.TextVar(&o.Level, "log-level", slog.LevelInfo, "log level: debug, info, warn or error")
fs.Usage = func() {
fmt.Fprintln(stderr, "Usage: demo [flags] [file ...]")
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
return o, nil, err
}
if o.Workers < 1 {
return o, nil, fmt.Errorf("-workers must be at least 1, got %d", o.Workers)
}
return o, fs.Args(), nil
}Custom flag types: flag.Value, TextVar and Func Important
In plain words: if a flag is not a number, string or duration, you teach flag the new type by giving it two methods, String and Set.
Common misunderstanding: "Set is called once with the whole command line." It is called once per occurrence of the flag, which is exactly why a repeatable flag (-tag a -tag b) appends in Set.
Definition: flag.Value is interface { String() string; Set(string) error }. String must work on a zero value because the flag package calls it on a freshly allocated zero to decide whether to print a default. An optional IsBoolFlag() bool method makes the flag usable without a value. flag.Getter adds Get() any.
1 fs.Var(&o.Tags, "tag", ...) register: remember the *ListFlag
2 Parse sees "-tag a" -> Tags.Set("a") -> Tags=[a]
3 Parse sees "--tag=b" -> Tags.Set("b") -> Tags=[a b]
4 Parse sees "-tag ' '" -> Tags.Set(" ") returns error "empty value"
5 Parse returns: invalid value " " for flag -tag: empty value| Need | Use | Why |
|---|---|---|
| A repeatable flag | custom Value that appends | Set runs per occurrence |
| A comma-separated list | custom Value that splits | one occurrence, many items |
An enum (text/json) | Func or custom Value that validates | reject early with a clear error |
A type that already has UnmarshalText (slog.Level, net/netip.Addr, time.Time) | TextVar | no new type needed |
A verb flag (-version) | BoolFunc | run code the moment it is seen |
slog.Level implements MarshalText/UnmarshalText, so fs.TextVar(&o.Level, "log-level", slog.LevelInfo, "...") accepts debug, info, warn, error and offsets such as info+2. A bad value fails with invalid value "loud" for flag -log-level: slog: level string "loud": unknown name.
Subcommands with one FlagSet per command Must-know
In plain words: git commit -m x and git push -f have different flags because each subcommand owns its own flag set; the program looks at the first word, picks the set, and lets it parse the rest.
Common misunderstanding: "Global flags before the subcommand just work." With plain flag they do not: tool -v greet parses -v against the top-level set, which knows nothing about greet. Either define shared flags on every command, parse a top-level set first and pass fs.Args() on, or move to a framework with persistent flags.
Definition: read os.Args[1] (the program name is os.Args[0]), switch on it, then call fs.Parse(os.Args[2:]) on that command's FlagSet.
1 $ tool greet -name Ada --json
2 os.Args = [tool greet -name Ada --json]
3 Run(args = [greet -name Ada --json])
4 switch args[0] -> "greet"
5 FlagSet "tool greet".Parse([-name Ada --json])
6 stdout: {"greeting":"hello, Ada"} exit 0The structure that keeps this testable is the one in subcmd.Run(args, env, stdout, stderr) int: it takes every input explicitly, writes only to the writers it is given, and returns the exit status. main is then one line: os.Exit(subcmd.Run(os.Args[1:], os.LookupEnv, os.Stdout, os.Stderr)).
// Package subcmd is a tiny multi-command CLI built on one FlagSet per
// subcommand. Run never calls os.Exit: it returns the exit code, so main
// stays a one-liner and tests call Run directly.
package subcmd
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"academy/cli-flags-env-logging/logx"
)
// Exit codes. 2 is what the flag package itself uses for usage errors.
const (
ExitOK = 0
ExitFailure = 1
ExitUsage = 2
)
// Version is overridden at build time:
//
// go build -ldflags "-X academy/cli-flags-env-logging/subcmd.Version=v1.2.3"
var Version = "dev"
// Env has the signature of os.LookupEnv.
type Env func(string) (string, bool)
const usageText = `Usage: tool <command> [flags]
Commands:
greet print a greeting (data goes to stdout)
log emit sample log records (logs go to stderr)
version print the version
Run "tool <command> -h" for the flags of one command.
`
// Run executes one command line (args excludes the program name).
func Run(args []string, env Env, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprint(stderr, usageText)
return ExitUsage
}
switch args[0] {
case "greet":
return runGreet(args[1:], env, stdout, stderr)
case "log":
return runLog(args[1:], stderr)
case "version":
fmt.Fprintln(stdout, Version)
return ExitOK
case "help", "-h", "-help", "--help":
fmt.Fprint(stdout, usageText)
return ExitOK
default:
fmt.Fprintf(stderr, "tool: unknown command %q\n\n%s", args[0], usageText)
return ExitUsage
}
}
// parse returns (code, true) when the caller must stop with that code.
func parse(fs *flag.FlagSet, args []string) (int, bool) {
err := fs.Parse(args)
switch {
case err == nil:
return 0, false
case errors.Is(err, flag.ErrHelp):
return ExitOK, true // -h is a request, not a failure
default:
return ExitUsage, true // the FlagSet already printed the error and usage
}
}
func runGreet(args []string, env Env, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("tool greet", flag.ContinueOnError)
fs.SetOutput(stderr)
// The environment supplies the default; an explicit flag still wins.
def := "world"
if v, ok := env("TOOL_NAME"); ok && v != "" {
def = v
}
name := fs.String("name", def, "who to greet (env TOOL_NAME)")
asJSON := fs.Bool("json", false, "print one JSON object instead of text")
if code, stop := parse(fs, args); stop {
return code
}
if fs.NArg() != 0 {
fmt.Fprintf(stderr, "tool greet: unexpected argument %q\n", fs.Arg(0))
return ExitUsage
}
if *asJSON {
if err := json.NewEncoder(stdout).Encode(map[string]string{"greeting": "hello, " + *name}); err != nil {
fmt.Fprintln(stderr, "tool greet:", err)
return ExitFailure
}
return ExitOK
}
fmt.Fprintf(stdout, "hello, %s\n", *name)
return ExitOK
}
func runLog(args []string, stderr io.Writer) int {
fs := flag.NewFlagSet("tool log", flag.ContinueOnError)
fs.SetOutput(stderr)
format := fs.String("format", "text", "log format: text or json")
verbose := fs.Bool("v", false, "debug level")
noTime := fs.Bool("no-time", false, "omit timestamps (golden output)")
if code, stop := parse(fs, args); stop {
return code
}
level := slog.LevelInfo
if *verbose {
level = slog.LevelDebug
}
logger, err := logx.New(stderr, logx.Options{Format: *format, Level: level, NoTime: *noTime})
if err != nil {
fmt.Fprintln(stderr, "tool log:", err)
return ExitUsage
}
ctx := logx.WithTraceID(context.Background(), "4bf92f35")
logger = slog.New(logx.ContextHandler{Handler: logger.Handler()})
logger.DebugContext(ctx, "cache lookup", "key", "user:42")
logger.InfoContext(ctx, "request handled", slog.Group("req", "method", "GET", "path", "/users/42"), "status", 200)
logger.WarnContext(ctx, "login failed", "user", "ada", "password", "hunter2")
return ExitOK
}// Command tool is the program the subcmd package powers.
package main
import (
"os"
"academy/cli-flags-env-logging/subcmd"
)
func main() {
os.Exit(subcmd.Run(os.Args[1:], os.LookupEnv, os.Stdout, os.Stderr))
}| Behaviour | Where it lives in the snippet |
|---|---|
tool with no arguments prints usage to stderr, exit 2 | Run, len(args) == 0 |
| unknown command: usage to stderr, exit 2, stdout empty | Run, default branch |
tool greet -h prints usage, exit 0 | parse, flag.ErrHelp |
tool help and tool version print to stdout, exit 0 | Run |
| extra positional argument: exit 2 | runGreet, fs.NArg() |
CLI frameworks: cobra, urfave/cli and kong Important
In plain words: flag is enough until you want nested commands, shell completion, generated help and man pages; then a framework saves a week.
Common misunderstanding: "A serious CLI must use cobra." The Go toolchain itself, gofmt and many small tools use flag. A framework is a dependency you maintain and a larger binary; take it when subcommand trees and completion pay for it.
| Aspect | flag (stdlib) | spf13/cobra | urfave/cli | alecthomas/kong |
|---|---|---|---|---|
| Style | imperative | commands as *cobra.Command values | declarative structs/slices | struct tags on a Go struct |
| Subcommands | hand-rolled with FlagSet | built in, nested | built in, nested | nested structs |
| Flag syntax | -x and --x | POSIX via pflag: -x, --xx, grouped -abc | -x, --xx, grouped short flags | --xx, -x |
| Persistent (inherited) flags | no | yes, PersistentFlags() | yes | yes (parent struct fields) |
| Shell completion | none | bash, zsh, fish, PowerShell | bash, zsh, fish, PowerShell | via plugin |
| Env var binding | manual | manual or viper | built in (EnvVars) | env:"NAME" tag |
| Generated docs | none | man pages, Markdown, YAML | man and Markdown (cli-docs) | help only |
| Typical use | small tools, go:generate | Kubernetes, Hugo, GitHub CLI | many mid-size tools | tools that prefer structs |
| Cost | none | cobra, pflag, mousetrap | no dependencies except the standard library | one module |
The cobra example in the snippet module builds the tree in a function so each test gets fresh flags; SilenceUsage and SilenceErrors stop cobra from printing usage for a runtime error and from printing the error twice (so main prints it once, to stderr, and chooses the exit code).
// Package cobraapp is the same kind of CLI as package subcmd, written with
// github.com/spf13/cobra: commands are values, flags belong to a command and
// help, usage and shell completion come for free.
package cobraapp
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
// NewRoot builds a fresh command tree. Building it in a function (not a
// package variable) keeps tests independent: every test gets its own flags.
func NewRoot() *cobra.Command {
var verbose bool
root := &cobra.Command{
Use: "app",
Short: "A cobra demo",
SilenceUsage: true, // do not print usage for runtime errors
SilenceErrors: true, // main prints the error once, to stderr
}
root.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output (inherited by subcommands)")
var shout bool
var times int
greet := &cobra.Command{
Use: "greet [name]",
Short: "Print a greeting",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := "world"
if len(args) == 1 {
name = args[0]
}
if times < 1 {
return fmt.Errorf("--times must be at least 1, got %d", times)
}
msg := "hello, " + name
if shout {
msg = strings.ToUpper(msg)
}
if verbose {
fmt.Fprintln(cmd.ErrOrStderr(), "greeting", name)
}
for i := 0; i < times; i++ {
fmt.Fprintln(cmd.OutOrStdout(), msg)
}
return nil
},
}
greet.Flags().BoolVar(&shout, "shout", false, "upper-case the greeting")
greet.Flags().IntVar(×, "times", 1, "how many times to print it")
root.AddCommand(greet)
return root
}Facts from each project's own README: urfave/cli lists "no dependencies except Go standard library", environment-variable lookup and shell completion; kong is configured with struct tags and has a "Switch on the command string" and an "Attach a Run(...) error method to each command" style; cobra's user guide describes the cmd/ directory with a bare main.go that only calls cmd.Execute().
Environment variables and 12-factor config Must-know
In plain words: the environment is a small key-value store the parent process hands to the child at start; it is the cheapest way to vary behaviour between laptop, CI and production without rebuilding.
Common misunderstanding: "An empty variable and a missing variable are the same." They are not: export APP_ADDR= sets it to "". Treating that as "unset" silently falls back to a default and hides a broken deployment; treating it as an error (as envcfg does) surfaces it.
Definition: os.Getenv(key) returns the value or "". os.LookupEnv(key) returns (value, present). os.Environ() returns a copy of the whole environment as key=value strings. os.Setenv/os.Unsetenv change only this process (and children started afterwards). os.ExpandEnv("$HOME/x") substitutes. In tests use t.Setenv, which restores the value and forbids t.Parallel.
1 shell: export APP_ADDR=:9100
2 shell: ./app fork/exec: child receives environ = [APP_ADDR=:9100 PATH=... ...]
3 app: os.LookupEnv("APP_ADDR") -> (":9100", true)
4 app: os.LookupEnv("APP_DEBUG") -> ("", false) unset
5 shell: APP_DEBUG= ./app
6 app: os.LookupEnv("APP_DEBUG") -> ("", true) set but empty
7 app: os.Getenv("APP_DEBUG") -> "" same as line 4| Source of variables | Typical use | Risk |
|---|---|---|
shell export | local development | lost on the next shell |
.env file loaded by joho/godotenv | local development only | accidentally committed; never override real env |
Kubernetes env: / envFrom: | deployment config | visible to anyone who can kubectl describe |
| Kubernetes Secret mounted as env | credentials | visible in /proc/<pid>/environ to the same user |
mounted file (/run/secrets/token) | credentials | needs a file path flag or env var pointing at it |
systemd Environment=/EnvironmentFile= | services on hosts | file permissions |
godotenv.Load() does not override variables that already exist, so a real environment always wins over a .env file (its README says existing environment variables take precedence); use it only when starting locally. Typed configuration helpers: kelseyhightower/envconfig fills a struct from APP_* variables via envconfig.Process("myapp", &s); knadh/koanf and spf13/viper merge several providers (files, env, flags, remote). For ten or fewer settings the standard library is shorter than any of them, as envcfg shows.
Configuration precedence Must-know
In plain words: when the same setting can come from several places, the closer to the operator's hand it is, the more it should win: flags beat env, env beats the file, the file beats the built-in default.
Common misunderstanding: "Precedence needs a special library." With flag it needs one idea: load the lower layers first and pass the result as the default of each flag. -h then prints the merged value, and a flag that was not given keeps the lower layer's value.
Definition: a total order over sources, applied from lowest to highest, with validation once at the end.
1 Defaults() Addr=":8080" Timeout=5s
2 file {"addr":":9000","timeout":"10s","debug":true}
3 Addr=":9000" Timeout=10s Debug=true
4 env APP_ADDR=:9100 APP_TIMEOUT=20s
5 Addr=":9100" Timeout=20s Debug=true
6 flags -timeout 30s
7 Addr=":9100" Timeout=30s Debug=true <- final| Source | Wins over | Loses to | Good for |
|---|---|---|---|
| compiled-in default | nothing | everything | safe local run |
| config file | defaults | env, flags | many settings, versioned per environment |
| environment | file | flags | per-deploy values, secrets |
| flag | everything | nothing | one-off override by the operator |
// Package envcfg layers configuration: defaults < file < environment < flags.
// The trick is that each layer becomes the default of the next one, so the
// flag package needs no extra bookkeeping.
package envcfg
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"strconv"
"time"
"academy/cli-flags-env-logging/logx"
)
// Config is the typed configuration of the service.
type Config struct {
Addr string `json:"addr"`
Timeout time.Duration `json:"timeout"`
Debug bool `json:"debug"`
Token logx.Secret `json:"token"`
}
// Lookup has the signature of os.LookupEnv, so tests inject a map.
type Lookup func(key string) (string, bool)
// Defaults returns the lowest layer.
func Defaults() Config { return Config{Addr: ":8080", Timeout: 5 * time.Second} }
// applyFile merges JSON over c. Absent keys keep their value.
func applyFile(c *Config, data []byte) error {
if len(data) == 0 {
return nil
}
// time.Duration is an int64 of nanoseconds in JSON; accept strings too.
var raw struct {
Addr *string `json:"addr"`
Timeout *string `json:"timeout"`
Debug *bool `json:"debug"`
Token *string `json:"token"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return fmt.Errorf("config file: %w", err)
}
if raw.Addr != nil {
c.Addr = *raw.Addr
}
if raw.Timeout != nil {
d, err := time.ParseDuration(*raw.Timeout)
if err != nil {
return fmt.Errorf("config file: timeout: %w", err)
}
c.Timeout = d
}
if raw.Debug != nil {
c.Debug = *raw.Debug
}
if raw.Token != nil {
c.Token = logx.Secret(*raw.Token)
}
return nil
}
// applyEnv overlays APP_ADDR, APP_TIMEOUT, APP_DEBUG and APP_TOKEN.
// A variable that is set but empty is an error, not "unset": os.LookupEnv
// exists precisely to tell the two apart.
func applyEnv(c *Config, lookup Lookup) error {
get := func(key string) (string, bool, error) {
v, ok := lookup(key)
if ok && v == "" {
return "", false, fmt.Errorf("%s is set but empty", key)
}
return v, ok, nil
}
if v, ok, err := get("APP_ADDR"); err != nil {
return err
} else if ok {
c.Addr = v
}
if v, ok, err := get("APP_TIMEOUT"); err != nil {
return err
} else if ok {
d, err := time.ParseDuration(v)
if err != nil {
return fmt.Errorf("APP_TIMEOUT: %w", err)
}
c.Timeout = d
}
if v, ok, err := get("APP_DEBUG"); err != nil {
return err
} else if ok {
b, err := strconv.ParseBool(v)
if err != nil {
return fmt.Errorf("APP_DEBUG: %w", err)
}
c.Debug = b
}
if v, ok, err := get("APP_TOKEN"); err != nil {
return err
} else if ok {
c.Token = logx.Secret(v)
}
return nil
}
// Load resolves the configuration. The token has no flag on purpose:
// command lines are visible in ps and shell history.
func Load(args []string, lookup Lookup, file []byte, stderr io.Writer) (Config, error) {
c := Defaults()
if err := applyFile(&c, file); err != nil {
return c, err
}
if err := applyEnv(&c, lookup); err != nil {
return c, err
}
fs := flag.NewFlagSet("app", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.StringVar(&c.Addr, "addr", c.Addr, "listen address (env APP_ADDR)")
fs.DurationVar(&c.Timeout, "timeout", c.Timeout, "request timeout (env APP_TIMEOUT)")
fs.BoolVar(&c.Debug, "debug", c.Debug, "debug mode (env APP_DEBUG)")
if err := fs.Parse(args); err != nil {
return c, err
}
if fs.NArg() > 0 {
return c, fmt.Errorf("unexpected argument %q", fs.Arg(0))
}
if c.Token == "" {
return c, errors.New("APP_TOKEN is required")
}
return c, nil
}Two details are deliberate. The token has no flag, because command lines are visible to every user through ps and stay in shell history; and its type is logx.Secret, so printing the whole Config with %+v or logging it cannot leak it (the test TestTokenNeverPrinted proves it).
Exit codes and os.Exit Must-know
In plain words: the exit status is the program's one-number answer to its caller: 0 means "it worked", anything else means "it did not", and the number says roughly why.
Common misunderstanding: "os.Exit is just a stronger return." It terminates the process immediately: deferred functions do not run, buffered writers are not flushed, and main cannot clean up. That is why you call it exactly once, in main, after everything else has returned.
Definition: a process exit status is a small integer (on Unix only the low 8 bits are kept, so os.Exit(256) reports 0). Falling off the end of main exits 0; os.Exit(n) exits n; an unrecovered panic exits 2 and prints panic: ... plus a stack to stderr; log.Fatal exits 1; a fatal runtime error such as fatal error: all goroutines are asleep - deadlock! exits 2.
| Code | Convention here | Source |
|---|---|---|
| 0 | success (and -h) | everywhere |
| 1 | the operation failed (I/O, network, bad data) | log.Fatal uses 1; project convention |
| 2 | usage error: unknown flag, bad argument | the flag package's own ExitOnError choice, and Go panics |
| 126, 127 | shell: not executable, command not found | the shell, not your program |
| 128+N | killed by signal N (130 is Ctrl+C, 137 is SIGKILL) | the shell reports it for you |
| 3-125 | your own documented codes (for example 3 "nothing to do") | document them in --help |
func main() {
// defer would be skipped by os.Exit below if it ran in the same function,
// so all real work lives in run() and its defers run before it returns.
os.Exit(run())
}
func run() int {
f, err := os.Create("out.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "tool:", err)
return 1
}
defer f.Close() // runs, because run returns normally
return 0
}Signals and shutdown (SIGINT, SIGTERM, signal.NotifyContext) are in OS Processes, Signals & Graceful Shutdown; here only the rule matters: translate "interrupted" into a non-zero status and still run your defers.
Standard streams: stdout for data, stderr for logs Must-know
In plain words: stdout is for what the program produces; stderr is for what it wants to say. A pipe carries only stdout, so tool | jq works even while the tool complains.
Common misunderstanding: "fmt.Println and log.Println both just print." One goes to stdout, the other to stderr. Logging a warning to stdout corrupts the next program in the pipeline; printing results to stderr makes tool > out.json produce an empty file.
Definition: file descriptors 0, 1 and 2, exposed as os.Stdin, os.Stdout, os.Stderr (all *os.File, all io.Reader/io.Writer). The flag package, log and slog's default handler write usage and logs to stderr.
| Output | Stream | Reason |
|---|---|---|
results (--json, lists, generated code) | stdout | consumed by pipes and files |
| usage text after a mistake | stderr | not part of the result |
usage text after -h or help | stdout | the user asked for it; tool -h | less works |
| error messages | stderr | with a non-zero exit status |
| logs and progress | stderr | keep stdout machine-clean |
| prompts for input | stderr (or the TTY) | stdout may be redirected |
Read input from stdin when no file argument is given (the Unix convention, - meaning stdin); see The io Package for bufio.Scanner and io.Copy patterns. In tests, pass bytes.Buffer writers instead of the real streams, as subcmd.Run does.
The log package and its limits Important
In plain words: log prints one timestamped line to stderr. It is fine for a small tool and too thin for a service.
Common misunderstanding: "log.Fatal logs an error and shuts down cleanly." It calls os.Exit(1) right after writing, so no defer runs. Inside a goroutine other than main it still kills the whole process. log.Panic panics instead, which can be recovered.
Definition: log.New(w, prefix, flags) makes a *log.Logger; the package has a standard logger (log.Println, log.Printf, log.Fatal*, log.Panic*). Flags: log.LstdFlags (date and time), Lmicroseconds, Lshortfile, Llongfile, LUTC, Lmsgprefix. It has no levels, no fields and no way to filter; encoding structure means formatting your own string.
// What log.Fatal does (simplified; log.go documents it as Print followed by os.Exit(1)):
// func Fatal(v ...any) {
// std.Print(v...)
// os.Exit(1)
// }
func main() {
defer cleanup() // NEVER runs: log.Fatal exits first
f, err := os.Open("config.json")
if err != nil {
log.Fatal(err) // writes "2026/11/26 10:00:00 open config.json: no such file..." and exits 1
}
_ = f
}Use log.Fatal only in a throwaway main or a TestMain; in everything else return the error to a main that prints it and exits once. slog.SetDefault also redirects the old log package through the new handler, so legacy log.Printf calls in dependencies become structured records at Info level (a level you control with slog.SetLogLoggerLevel).
log/slog basics: Logger, Handler, Level, Attr, Group Must-know
In plain words: a Logger is the thing you call; a Handler is the thing that decides whether and how to write; a record carries the message, the level, a time and a list of key-value attributes between them.
Common misunderstanding: "slog is a logging backend." It is a front end and an interface (slog.Handler) with two built-in backends. You can swap the handler for zap's or your own without touching the call sites; that is the point of having it in the standard library.
Definition: slog.New(h Handler) *Logger; methods Debug, Info, Warn, Error (and ...Context variants) take msg string, args ...any. args alternate key, value; a stray odd argument becomes !BADKEY=value (and go vet reports call to slog.Logger.Info missing a final value). An Attr is a typed key-value (slog.String, Int, Bool, Duration, Time, Any, Group). A Level is an integer: Debug -4, Info 0, Warn 4, Error 8, with room between for your own (slog.Level(-8) as TRACE).
1 logger.Info("request handled", "status", 200, slog.Group("req", "method", "GET"))
2 Logger builds Record{Time, Level=INFO(0), Message, Attrs[status=200, req{method=GET}]}
3 handler.Enabled(ctx, INFO)? yes
4 handler.Handle(ctx, record)
5 TextHandler: time=... level=INFO msg="request handled" status=200 req.method=GET
6 JSONHandler: {"time":"...","level":"INFO","msg":"request handled","status":200,"req":{"method":"GET"}}| Concept | Type / function | Behaviour |
|---|---|---|
| Level threshold | HandlerOptions.Level (a slog.Leveler) | default Info; use *slog.LevelVar to change at runtime |
| Time | built-in key time | removed by returning an empty Attr from ReplaceAttr |
| Message | built-in key msg | a user attribute named msg duplicates it; avoid |
| Source | HandlerOptions.AddSource | adds source (function, file, line); costs a stack lookup |
| Group | slog.Group("req", ...) or logger.WithGroup("req") | text prints req.method, JSON nests them under a req object |
| Default logger | slog.Default() | writes through the log package's default output |
| Discard | slog.DiscardHandler (Go 1.24) | every level disabled |
TextHandler quotes values that contain spaces (msg="request handled") and prints errors with their Error() text; JSONHandler writes error values as strings. Both are safe for concurrent use.
Loggers in practice: With, LogAttrs, context, SetDefault Must-know
In plain words: build one configured logger at startup, derive child loggers that carry fixed attributes (With), and pass a context when you have one so handlers can read request-scoped values.
Common misunderstanding: "logger.With(...) mutates the logger." It returns a new Logger sharing the same handler; the receiver is unchanged. Likewise WithGroup qualifies only what is logged through the returned logger afterwards.
Definition: logger.With("component", "billing") pre-attaches attributes once (handlers can pre-format them, so it is cheaper than repeating them). logger.LogAttrs(ctx, level, msg, attrs...) takes only slog.Attr values and is the allocation-lean path for hot code. logger.InfoContext(ctx, ...) passes the context to the handler. slog.SetDefault(l) installs l for the top-level functions and the log package.
base := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
slog.SetDefault(base) // slog.Info(...) and log.Printf(...) now use it
svc := base.With("component", "billing") // new logger, same handler
svc.LogAttrs(ctx, slog.LevelWarn, "retrying",
slog.Int("attempt", 3),
slog.Duration("backoff", 800*time.Millisecond),
slog.Any("err", err)) // slog.Any keeps the error value; the handler formats it| Style | Allocations | Type safety | When |
|---|---|---|---|
logger.Info("m", "k", v) | boxes v into any | none: odd count caught by vet only | everyday code |
logger.Info("m", slog.Int("k", n)) | no boxing for scalars | typed | normal |
logger.LogAttrs(ctx, lvl, "m", attrs...) | lowest | typed | hot paths |
slog.Any("k", v) | boxes v | none | structs, errors, maps |
slog.LogValuer on a type | evaluated only if the level is enabled | typed | expensive or sensitive values |
The logx test TestDisabledLevelSkipsLogValuer shows the cost model: with the level at Warn, logger.Info("skipped", "v", lazy{}) never calls LogValue, because the handler's Enabled check runs first.
Handlers you write: ReplaceAttr, redaction, trace ids, sampling Important
In plain words: you can rewrite or drop any attribute with ReplaceAttr, and you can wrap a handler in your own to add attributes from the context, sample, or fan out to two destinations.
Common misunderstanding: "A wrapper handler only needs Handle." It also needs WithAttrs and WithGroup, and both must re-wrap their result. If they return the inner handler, the wrapper silently disappears the first time anyone calls logger.With(...). testing/slogtest (added in Go 1.21) checks exactly these contracts.
Definition: slog.Handler has four methods: Enabled(ctx, level) bool, Handle(ctx, Record) error, WithAttrs([]Attr) Handler, WithGroup(string) Handler. Embedding the inner handler in a struct gives you the methods you do not override. ReplaceAttr func(groups []string, a Attr) Attr is called for every attribute except groups themselves, and for the built-in time, level, msg and source keys (with groups empty).
1 l.InfoContext(ctx, "login", "user", "ada", "password", "hunter2")
2 ContextHandler.Handle: ctx has trace id -> r.AddAttrs(trace_id=4bf92f35)
3 Sampler.Handle: Info and counter says drop? -> return nil (Warn and above always pass)
4 JSONHandler.Handle: for each attr -> ReplaceAttr(groups, attr)
5 key "password" is sensitive -> value becomes "[REDACTED]"
6 key "time" and NoTime -> empty Attr, omitted
7 write {"level":"INFO","msg":"login","user":"ada","password":"[REDACTED]","trace_id":"4bf92f35"}| Technique | Where it acts | Strength | Weakness |
|---|---|---|---|
ReplaceAttr key list | every attribute, any depth | catches mistakes at the call site | only keys you listed; a value inside a message string is untouched |
slog.LogValuer on Secret | the type | secret can never print, even via %v and JSON | developers must use the type |
ContextHandler | per record | trace id on every line without passing it everywhere | needs InfoContext; plain Info has no ctx |
Sampler | per record | caps volume of Info/Debug | drops are invisible; counters are per process |
MultiHandler-style fan-out | per record | text to stderr and JSON to a file | you must handle one destination failing |
// Package logx builds slog loggers for command-line programs: text or JSON,
// a runtime-adjustable level, a custom TRACE level, redaction and no-time
// output for golden tests.
package logx
import (
"fmt"
"io"
"log/slog"
"strings"
)
// LevelTrace is below Debug. slog levels are plain integers.
const LevelTrace = slog.Level(-8)
// Options configures New.
type Options struct {
Format string // "text" or "json"
Level slog.Leveler // nil means Info
NoTime bool // drop the time attribute (golden output)
AddSource bool
}
// sensitive lists attribute keys whose values are never printed.
var sensitive = map[string]bool{
"password": true, "token": true, "authorization": true,
"secret": true, "api_key": true, "cookie": true,
}
// New returns a logger that writes to w.
func New(w io.Writer, o Options) (*slog.Logger, error) {
ho := &slog.HandlerOptions{
Level: o.Level,
AddSource: o.AddSource,
ReplaceAttr: replaceAttr(o.NoTime),
}
var h slog.Handler
switch strings.ToLower(o.Format) {
case "", "text":
h = slog.NewTextHandler(w, ho)
case "json":
h = slog.NewJSONHandler(w, ho)
default:
return nil, fmt.Errorf("unknown log format %q (want text or json)", o.Format)
}
return slog.New(h), nil
}
func replaceAttr(noTime bool) func([]string, slog.Attr) slog.Attr {
return func(groups []string, a slog.Attr) slog.Attr {
// Built-in attributes live at the top level only.
if len(groups) == 0 {
switch a.Key {
case slog.TimeKey:
if noTime {
return slog.Attr{} // an empty Attr is omitted
}
case slog.LevelKey:
if l, ok := a.Value.Any().(slog.Level); ok && l == LevelTrace {
return slog.String(slog.LevelKey, "TRACE")
}
}
}
if sensitive[strings.ToLower(a.Key)] {
return slog.String(a.Key, "[REDACTED]")
}
return a
}
}
// Secret hides its value from every slog handler, from %v and from JSON.
type Secret string
// LogValue implements slog.LogValuer.
func (Secret) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }
// String implements fmt.Stringer so %s and %v do not leak either.
func (Secret) String() string { return "[REDACTED]" }
// MarshalText keeps encoding/json from leaking the value.
func (Secret) MarshalText() ([]byte, error) { return []byte("[REDACTED]"), nil }package logx
import (
"context"
"log/slog"
"sync/atomic"
)
type traceKey struct{}
// WithTraceID stores a correlation id in ctx.
func WithTraceID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, traceKey{}, id)
}
// ContextHandler adds trace_id from the context of each call to the record.
// It only sees the context when callers use the *Context methods
// (InfoContext, LogAttrs...); plain Info passes context.Background().
type ContextHandler struct{ slog.Handler }
// Handle implements slog.Handler.
func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
if id, ok := ctx.Value(traceKey{}).(string); ok {
r.AddAttrs(slog.String("trace_id", id))
}
return h.Handler.Handle(ctx, r)
}
// WithAttrs must re-wrap the result or the wrapper is lost after logger.With.
func (h ContextHandler) WithAttrs(as []slog.Attr) slog.Handler {
return ContextHandler{h.Handler.WithAttrs(as)}
}
// WithGroup must re-wrap as well.
func (h ContextHandler) WithGroup(name string) slog.Handler {
return ContextHandler{h.Handler.WithGroup(name)}
}
// Sampler passes every record at Warn and above and one in every N records
// below Warn. The counter is shared by all loggers derived from it.
type Sampler struct {
slog.Handler
n uint64
counter *atomic.Uint64
}
// NewSampler wraps next. n <= 1 disables sampling.
func NewSampler(next slog.Handler, n uint64) Sampler {
return Sampler{Handler: next, n: n, counter: new(atomic.Uint64)}
}
// Handle implements slog.Handler.
func (s Sampler) Handle(ctx context.Context, r slog.Record) error {
if r.Level < slog.LevelWarn && s.n > 1 && (s.counter.Add(1)-1)%s.n != 0 {
return nil
}
return s.Handler.Handle(ctx, r)
}
// WithAttrs re-wraps so the sampler survives logger.With.
func (s Sampler) WithAttrs(as []slog.Attr) slog.Handler {
s.Handler = s.Handler.WithAttrs(as)
return s
}
// WithGroup re-wraps so the sampler survives logger.WithGroup.
func (s Sampler) WithGroup(name string) slog.Handler {
s.Handler = s.Handler.WithGroup(name)
return s
}Caveat about groups: attributes added by Handle (trace_id) land inside whatever group is open on the handler (WithGroup("req") makes it req.trace_id). Either add the trace id before grouping or accept the nesting.
Structured logging practice: keys, PII, sampling, correlation ids Must-know
In plain words: pick stable key names, put facts in attributes and not in sentences, never write personal data, and stamp every line of one request with the same id.
Common misunderstanding: "More logging is safer." Volume costs money and hides the line you need, and every extra field is a chance to leak a credential. Log events that someone will query, at the level they will filter on.
| Rule | Do | Avoid |
|---|---|---|
| Message | constant text: "payment failed" | interpolated: "payment 8812 failed" (cannot group by message) |
| Keys | snake_case, same everywhere: user_id, order_id, duration_ms | userId in one file and uid in another |
| Units | slog.Duration or a unit in the key | "took": 1.5 |
| Errors | slog.Any("err", err) or key error | err.Error() pasted into the message |
| PII | ids and hashed values | e-mail, phone, token, card number, request bodies |
| Secrets | Secret type and ReplaceAttr | trusting reviewers to notice |
| Level | Error = needs action; Warn = degraded; Info = business events; Debug = developer | everything at Info |
| Correlation | one request_id or W3C trace_id on every record | one id per layer that nobody can join |
Sampling keeps cost bounded: always keep Warn and above, sample the noisy Info/Debug lines, and count what you drop. Rate-based sampling in the logger is a blunt tool; head-based or tail-based sampling of traces belongs to the pipeline (see Observability). For correlation across services (propagating traceparent through headers and queues) see Messaging Observability & Tracing.
Logging in libraries versus applications Important
In plain words: an application owns the output; a library is a guest and must not talk unless asked.
Common misunderstanding: "A library should log.Printf its errors so nothing is lost." It should return them. Printing steals the application's formatting, destination and level decisions, and clutters tests.
Definition: the library takes a *slog.Logger (an option or a field), defaults to slog.New(slog.DiscardHandler) (Go 1.24; before that, a handler whose Enabled returns false), never calls log.Fatal, os.Exit or panic for expected failures, and never writes to the global default logger.
// Package widget is a library: it logs only if the caller hands it a logger.
package widget
import (
"context"
"log/slog"
)
// Widget does some work and reports it through an injected logger.
type Widget struct{ log *slog.Logger }
// Option configures a Widget.
type Option func(*Widget)
// WithLogger sets the logger. A nil logger keeps the silent default.
func WithLogger(l *slog.Logger) Option {
return func(w *Widget) {
if l != nil {
w.log = l
}
}
}
// New returns a silent Widget unless WithLogger is given. slog.DiscardHandler
// (Go 1.24) reports every level as disabled, so no attribute is evaluated.
func New(opts ...Option) *Widget {
w := &Widget{log: slog.New(slog.DiscardHandler)}
for _, o := range opts {
o(w)
}
return w
}
// Run does the work. The library never calls log.Fatal or os.Exit and never
// writes to the global logger.
func (w *Widget) Run(ctx context.Context, n int) error {
w.log.DebugContext(ctx, "widget run", "n", n)
if n < 0 {
w.log.WarnContext(ctx, "negative input", "n", n)
}
return ctx.Err()
}| Concern | Application | Library |
|---|---|---|
| Chooses handler, level, destination | yes | no |
Calls slog.SetDefault | once, in main | never |
Uses package-level slog.Info | acceptable in small tools | avoid; take a logger |
| On failure | log once at the top, exit | return an error, optionally log Debug detail |
Adds component attribute | optional | yes, via logger.With("component", ...) |
Third-party loggers: zap and zerolog Good to know
In plain words: before Go 1.21 the community built fast structured loggers; they are still excellent and now plug in behind slog.
Common misunderstanding: "slog is slower, so use zap everywhere." slog is fast enough for most services; zap and zerolog matter when logging is on a measured hot path (their READMEs advertise zero or near-zero allocation). Measure with your own benchmark before paying for a dependency.
| Aspect | log/slog | go.uber.org/zap | github.com/rs/zerolog |
|---|---|---|---|
| In the standard library | yes | no | no |
| API style | Info(msg, kv...), LogAttrs | zap.Logger typed fields, SugaredLogger | chained builder log.Info().Str("k","v").Msg("m") |
| Allocations | low with LogAttrs | very low (typed fields) | "Zero Allocation JSON Logger" |
| Pluggable backend | slog.Handler interface | has an slog handler bridge | has an slog handler bridge |
| Levels | integers, extensible | fixed enum plus dynamic AtomicLevel | fixed enum |
| Choose when | default for new code | hot paths, existing zap codebase | JSON-only, chained style |
Because slog.Handler is an interface, you can keep slog call sites and put zap or zerolog behind them with their slog adapters, which is the migration path for old code.
Verbosity flags, --json output and TTY detection Important
In plain words: humans want colour, a progress bar and friendly text; scripts want plain lines or JSON. The same program decides which to produce by asking where its output goes.
Common misunderstanding: "Detect the terminal once and assume it for the whole run." Stdout and stderr are independent: tool > out.txt leaves stderr on the terminal. Ask about the stream you are writing to.
Definition: golang.org/x/term.IsTerminal(int(f.Fd())) reports whether a file descriptor is a terminal. Honour the NO_COLOR convention (any non-empty value disables colour, see no-color.org). Offer -v/--verbose (debug level), -q/--quiet, and --json or --format json for data. Keep log format (--log-format) separate from data format (--json): one is for operators on stderr, the other for pipes on stdout.
// Package ttyout adapts progress output to where stderr is going.
package ttyout
import (
"fmt"
"io"
"os"
"golang.org/x/term"
)
// IsTerminal reports whether f is an interactive terminal.
func IsTerminal(f *os.File) bool { return term.IsTerminal(int(f.Fd())) }
// ColorEnabled follows https://no-color.org: any non-empty NO_COLOR disables colour.
func ColorEnabled(tty bool, lookup func(string) (string, bool)) bool {
if v, ok := lookup("NO_COLOR"); ok && v != "" {
return false
}
return tty
}
// Progress writes one progress update to w. On a terminal it rewrites the
// same line with a carriage return; otherwise (pipe, file, CI log) it emits
// a plain line only at every 25 percent so logs stay readable.
func Progress(w io.Writer, tty bool, done, total int) {
if total <= 0 {
return
}
pct := done * 100 / total
if tty {
fmt.Fprintf(w, "\rprocessed %d/%d (%d%%)", done, total, pct)
if done == total {
fmt.Fprintln(w)
}
return
}
if pct%25 == 0 && (done == total || done*4%total == 0) {
fmt.Fprintf(w, "processed %d/%d (%d%%)\n", done, total, pct)
}
} 1 tool process --input big.csv stderr is a TTY
2 Progress(w, tty=true, 3, 10) -> "\rprocessed 3/10 (30%)" rewrites the line
3 tool process --input big.csv 2> run.log stderr is a file
4 Progress(w, tty=false, 3, 10) -> (nothing) only at 25%, 50%, 75%, 100%
5 Progress(w, tty=false, 5, 10) -> "processed 5/10 (50%)\n"| Flag | Convention | Effect in the snippets |
|---|---|---|
-v, --verbose | repeatable in many tools | tool log -v lowers the level to Debug |
-q, --quiet | suppress non-error output | not implemented; add as slog.LevelError |
--json | machine-readable data on stdout | tool greet --json |
--log-format json | machine-readable logs on stderr | tool log -format json |
--no-color / NO_COLOR | disable ANSI colour | ttyout.ColorEnabled |
--version | print version, exit 0 | tool version |
Testing a CLI: Run(), buffers and testscript Must-know
In plain words: keep main to one line, test the function behind it with fake streams, and add a few end-to-end scripts that run the real command.
Common misunderstanding: "To test a CLI you must build the binary and shell out." Unit tests of Run(args, env, stdout, stderr) cover flags, output and exit codes in microseconds; testscript covers the rest, including pipes and files, without a hand-written exec.Command.
Definition: testscript.Run(t, testscript.Params{Dir: "testdata"}) runs .txtar scripts; testscript.RunMain (call it from TestMain) registers your main under a command name so a script can exec tool ... without a separate go build. Script commands include exec, ! (expect failure), stdout/stderr (regexp match), cmp, env, and files embedded in the archive.
package main
import (
"os"
"testing"
"github.com/rogpeppe/go-internal/testscript"
"academy/cli-flags-env-logging/subcmd"
)
// TestMain registers "tool" as a command that testscript scripts can exec.
// testscript re-runs this test binary under that name, so the real main
// path (flags, exit code, stdout, stderr) is what the scripts exercise.
func TestMain(m *testing.M) {
os.Exit(testscript.RunMain(m, map[string]func() int{
"tool": func() int {
return subcmd.Run(os.Args[1:], os.LookupEnv, os.Stdout, os.Stderr)
},
}))
}
func TestScripts(t *testing.T) {
testscript.Run(t, testscript.Params{Dir: "testdata"})
}# an unknown command exits 2 with usage on stderr and nothing on stdout
! exec tool frobnicate
! stdout .
stderr 'unknown command "frobnicate"'
stderr 'Usage: tool <command>'
# a bad flag exits 2
! exec tool greet -nope
stderr 'flag provided but not defined: -nope'
# -h is not a failure
exec tool greet -h
stderr 'Usage of tool greet:'| Level | Tool | What it proves | Speed |
|---|---|---|---|
| Parse function | Parse(args, &stderr) in a table test | flags, defaults, error texts | microseconds |
| Command function | Run(args, env, &out, &err) | output, streams, exit code | microseconds |
| Real binary | testscript with exec tool | the actual main, pipes, files | tens of ms |
| Cobra | cmd.SetArgs, SetOut, SetErr, Execute() | the same, via the framework | microseconds |
| Handlers | testing/slogtest.TestHandler | a custom Handler honours the contract | microseconds |
| Env in tests | t.Setenv | restores the variable automatically | n/a |
Running another program from your CLI (os/exec: exec.Command, CombinedOutput, process groups) is covered in OS Processes, Signals & Graceful Shutdown; here the one rule is to pass context and to wire the child's stdout and stderr deliberately.
Shipping a CLI: go install, ldflags and GoReleaser Good to know
In plain words: Go users can install your tool with one command from the source repository; everyone else needs prebuilt binaries per OS and architecture.
Common misunderstanding: "go install and go build produce different programs." The same compiler runs; go install puts the result in $GOBIN (default $GOPATH/bin), and go install module/path/cmd/tool@latest builds a specific version outside any module.
| Step | Command | Note |
|---|---|---|
| Install from source | go install example.com/me/tool/cmd/tool@v1.2.3 | needs a Go toolchain |
| Embed the version | go build -ldflags "-X academy/cli-flags-env-logging/subcmd.Version=v1.2.3" | sets a string variable at link time |
| Read build info | runtime/debug.ReadBuildInfo() | module version and VCS stamp without -ldflags |
| Cross-compile | GOOS=linux GOARCH=arm64 go build | no extra toolchain needed |
| Release many targets | goreleaser release | archives, checksums, Homebrew taps, GitHub release (GoReleaser quick start) |
| Static binary | CGO_ENABLED=0 go build | ideal for scratch containers |
The project layout (cmd/tool/main.go, internal/), Makefiles and Docker multi-stage builds are in Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds.
Mechanics
Exact error texts and values Must-know
Every text below was produced by the tests in the snippet module or read in the standard-library source.
| Situation | Text or value |
|---|---|
| unknown flag | flag provided but not defined: -nope |
| flag without its value | flag needs an argument: -addr |
| bad integer | invalid value "x" for flag -workers: parse error |
custom Set rejects | invalid value " " for flag -tag: empty value |
-h under ContinueOnError | Parse returns flag: help requested (flag.ErrHelp) |
| defining a flag twice | panic: flag redefined: addr |
flag.CommandLine after a bad flag | usage on stderr, os.Exit(2) |
odd key-value list in slog | !BADKEY=k in the output; go vet: call to slog.Logger.Info missing a final value |
| unknown level text | slog: level string "loud": unknown name |
| cobra: too many arguments | accepts at most 1 arg(s), received 2 |
| cobra: unknown flag | unknown flag: --loud |
| cobra: unknown command | unknown command "nope" for "app" |
| env set but empty | APP_ADDR is set but empty (our rule, not the runtime's) |
| bad bool in env | APP_DEBUG: strconv.ParseBool: parsing "maybe": invalid syntax |
| bad duration in env | APP_TIMEOUT: time: invalid duration "soon" |
Every knob of HandlerOptions, Logger and flag Important
| Knob | Type | Default | Effect |
|---|---|---|---|
HandlerOptions.Level | slog.Leveler | Info | minimum level; pass *slog.LevelVar for runtime changes |
HandlerOptions.AddSource | bool | false | adds file and line of the call site |
HandlerOptions.ReplaceAttr | func([]string, Attr) Attr | nil | rewrite, rename or drop attributes |
slog.SetLogLoggerLevel | func(Level) Level | Info | level assigned to legacy log calls routed through slog |
flag.ContinueOnError | ErrorHandling | n/a | return the error |
flag.ExitOnError | ErrorHandling | the global set's mode | print usage, os.Exit(2) (-h: 0) |
flag.PanicOnError | ErrorHandling | n/a | panic with the error |
FlagSet.Usage | func() | prints defaults | your own help text |
FlagSet.SetOutput | io.Writer | stderr | where usage and errors go |
log.SetFlags | int | LstdFlags | date, time, file, microseconds |
log.SetOutput | io.Writer | stderr | destination of the standard logger |
Level arithmetic and custom levels Good to know
A slog.Level is an int; Debug is -4, Info 0, Warn 4, Error 8 so that you can insert levels between them. logx.LevelTrace is slog.Level(-8). The built-in handlers print unknown levels as the nearest name plus an offset (DEBUG-4 for -8), so the snippet renames it in ReplaceAttr to TRACE. Level.String() and ParseLevel-style text (debug, info+2) come from MarshalText/UnmarshalText.
| Text | Level | Note |
|---|---|---|
debug | -4 | |
info | 0 | |
warn | 4 | |
error | 8 | |
info+2 | 2 | between Info and Warn |
debug-4 | -8 | what LevelTrace prints without renaming |
Solving the classic problems
| Problem | Solution | How | Cost or limitation |
|---|---|---|---|
| Typo in a flag kills a test run | own FlagSet with ContinueOnError | Parse(args, &stderr) returns the error | a few more lines |
Secret in ps output | read from env or file | no flag for it | file permissions matter |
| Secret in logs | Secret type with LogValue, ReplaceAttr list | redaction in the logger | defence in depth, not proof |
| Defers skipped | os.Exit(run()) | exit once in main | one extra function |
| Logs corrupt a pipe | logs to stderr, data to stdout | explicit writers | none |
| Can't tell unset from empty | LookupEnv | treat "set but empty" explicitly | one more branch |
| Different config per environment | layered precedence | defaults, file, env, flags | document the order |
| Global flags before subcommand | persistent flags in cobra or repeat in each set | framework | dependency |
| No trace id in logs | ContextHandler | add from ctx | callers must pass ctx |
| Log volume explosion | level discipline plus Sampler | drop Info/Debug 9 of 10 | drops invisible |
| Library prints to stdout | injected logger, discard default | WithLogger | one option |
| Unreadable JSON in a terminal | TTY detection | text on TTY, JSON otherwise | two formats to test |
Slow go vet surprises | run go vet | catches odd slog key lists | none |
Replace log.Fatal in an application
// Before: skips defers, untestable, kills the process from deep code.
func load(path string) Config {
data, err := os.ReadFile(path)
if err != nil {
log.Fatalf("read config: %v", err)
}
// ...
}
// After: return the error; main decides what to print and which code to use.
func load(path string) (Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("read config: %w", err)
}
_ = data
return Config{}, nil
}A logger at startup in an application
func newLogger(format string, verbose bool, w io.Writer) (*slog.Logger, error) {
level := slog.LevelInfo
if verbose {
level = slog.LevelDebug
}
return logx.New(w, logx.Options{Format: format, Level: level})
}Call it once in run(), call slog.SetDefault only if third-party code uses the global logger, and pass the *slog.Logger (or a child via With) into constructors.
Choosing
| Situation | Choose | Reason |
|---|---|---|
| One binary, one purpose, a handful of flags | flag | no dependency |
| Several subcommands, little nesting | FlagSet per command | clear, testable |
| Deep command tree, completion, docs | cobra (or kong for struct style) | built in |
| Declarative style with env binding | urfave/cli | env and files in the definition |
| Containerised service | env vars plus flags | 12-factor |
| Many settings, files, hot reload | koanf or viper | multiple providers |
| Local development secrets | .env via godotenv | convenience only |
| New service logging | log/slog JSON to stderr/stdout | standard, pluggable |
| Interactive tool logging | slog text handler to stderr | readable |
| Hot-path logging, measured | zap or zerolog behind slog | allocations |
| Library | accept *slog.Logger, discard by default | guest behaviour |
| Test the real binary | testscript | scripts in .txtar |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One binary, a config struct built in main from flags and environment, one logger writing JSON to stdout or stderr, and a process manager (systemd, a container runtime) that collects it and acts on the exit status. Example: a billing service run as billing serve and billing migrate subcommands; migrate returns exit 1 on a failed migration so the deploy pipeline stops.
Modular monolith and multiple databases
Modules share the process and therefore the logger and the config, but each should get its own section of the config struct and its own child logger (logger.With("module", "inventory")). Example: the inventory and ordering modules each have DATABASE_URL_INVENTORY and DATABASE_URL_ORDERING; -h prints both so operators see them in one place. The SQL below is what an operator runs to confirm each module connected under its own name (the connection string sets application_name):
-- PostgreSQL: which service instance holds which connection, by the name the app set
SELECT application_name, state, count(*) AS connections
FROM pg_stat_activity
WHERE application_name LIKE 'billing-%'
GROUP BY application_name, state
ORDER BY application_name;Microservices
Each service is its own CLI with the same conventions (same flag names, same LOG_LEVEL, same JSON keys), because the platform's dashboards and alerts depend on them. A shared internal package builds the logger and the config loader. A request that crosses services carries a traceparent header; the ContextHandler pattern stamps its trace id on every record in every service, which is what lets a log search follow one request across four processes. Example: gateway receives a request, creates a trace id, calls orders over gRPC; both services log trace_id and the log pipeline joins them. Kubernetes command:/args: map to argv and env: to the environment, so the 12-factor layers above are exactly what a Deployment manifest sets.
Distributed data: replicas, caches and log pipelines
Logs written to stdout are collected by an agent and shipped to a store; there is no ordering guarantee between hosts, so the timestamp and the trace id are the only join keys. Clock skew means two services can appear to log in the wrong order. Rotating files from inside the Go process is an anti-pattern in containers: write to the stream and let the platform rotate. Config that comes from a remote store (a config service, a secret manager) adds a failure mode at startup: decide whether the process refuses to start (fail fast, exit 1) or runs on cached values, and log which one. A cached config can be stale across replicas; include a config version in a startup log line so you can see which replicas run which version.
Scaling path: 1x, 10x, 100x
| Scale | Logging | Configuration | CLI |
|---|---|---|---|
| 1x: one host | text to stderr, journalctl or a file | flags and env | flag and FlagSet |
| 10x: a few services | JSON, shipped by an agent, trace_id everywhere | shared config package, env from the orchestrator | shared internal CLI conventions, cobra if commands grow |
| 100x: many teams | sampling in the pipeline, retention tiers, PII scrubbing as a gate | typed schema per service, central secrets manager | goreleaser for admin tools, versioned binaries, testscript in CI |
For PHP/Laravel developers
Laravel's Artisan (built on Symfony Console) registers commands as classes with a $signature string (greet {name} {--shout}) and shows help automatically; Symfony Console has InputInterface/OutputInterface, with STDERR through ConsoleOutput::getErrorOutput(). PHP's configuration comes from .env loaded into the framework at boot (env('APP_DEBUG')), and logging goes through Monolog channels configured in config/logging.php. Go has no framework boot, so each of those is a function you call in main.
| Concern | Laravel / PHP | Go |
|---|---|---|
| Command definition | Artisan $signature or Symfony configure() | FlagSet or cobra.Command |
| Help text | generated | -h prints PrintDefaults; cobra generates more |
| Exit status | return Command::SUCCESS / FAILURE | os.Exit(code) once in main |
| Output streams | $this->line() to stdout, $this->error() to stderr | os.Stdout, os.Stderr |
| Config | .env, config() | os.LookupEnv, struct, precedence |
| Logging | Log::info('msg', ['id' => 1]) via Monolog | logger.Info("msg", "id", 1) via slog |
| Per-request context | Log::withContext([...]) | logger.With(...) or a ContextHandler |
| Log channels (stack, daily, stderr) | config/logging.php | one handler, or a fan-out handler |
| Deployment | php artisan inside the app | a static binary per tool |
// Laravel: context added once, merged into every later record on that channel.
Log::withContext(['request_id' => $requestId]);
Log::info('payment failed', ['order_id' => 8812]);The Go equivalent keeps the same two ideas, a message and a context map, but the context is typed slog.Attr values and the "channel" is whichever Handler you passed to slog.New.
Lab
Expected, not run for the parts that need a network or a real TTY. The commands below that print output were run on the host with the snippet module (Go 1.27.4 was installed; the module itself declares go 1.24).
cd docs/snippets/go/cli-flags-env-logging/go
go build -ldflags "-X academy/cli-flags-env-logging/subcmd.Version=v1.2.3" -o /tmp/tool ./cmd/tool
/tmp/tool version # v1.2.3 exit 0
/tmp/tool greet # hello, world exit 0
TOOL_NAME=Ada /tmp/tool greet # hello, Ada env default
TOOL_NAME=Ada /tmp/tool greet -name Bob # hello, Bob flag beats env
/tmp/tool greet -name Bob --json # {"greeting":"hello, Bob"}
/tmp/tool greet -nope # stderr: flag provided but not defined: -nope + usage, exit 2
/tmp/tool greet -h # stderr: Usage of tool greet: ... exit 0
/tmp/tool frobnicate # stderr: tool: unknown command "frobnicate" + usage, exit 2Observed usage text (exit status 2 after the error line):
flag provided but not defined: -nope
Usage of tool greet:
-json
print one JSON object instead of text
-name string
who to greet (env TOOL_NAME) (default "world")Experiment 1: logs on stderr, data on stdout.
/tmp/tool log -no-time -v
# level=DEBUG msg="cache lookup" key=user:42 trace_id=4bf92f35
# level=INFO msg="request handled" req.method=GET req.path=/users/42 status=200 trace_id=4bf92f35
# level=WARN msg="login failed" user=ada password=[REDACTED] trace_id=4bf92f35
/tmp/tool log -no-time 2>/dev/null | wc -c # 0 (nothing on stdout)Experiment 2: the same records as JSON.
/tmp/tool log -no-time -format json -v
# {"level":"DEBUG","msg":"cache lookup","key":"user:42","trace_id":"4bf92f35"}
# {"level":"INFO","msg":"request handled","req":{"method":"GET","path":"/users/42"},"status":200,"trace_id":"4bf92f35"}
# {"level":"WARN","msg":"login failed","user":"ada","password":"[REDACTED]","trace_id":"4bf92f35"}Experiment 3: the test suite, including the race detector and the testscript scripts.
gofmt -l . # no output
go vet ./... # no output
go test -race ./... # ok for flagset, subcmd, envcfg, logx, widget, ttyout, cobraapp, cmd/toolExperiment 4 (expected, not run): confirm the TTY switch by running a command that calls ttyout.Progress once in a terminal and once with 2> run.log; the first rewrites one line with \r, the second writes four plain lines.
Experiment 5 (expected, not run): run go vet on a file containing logger.Info("odd", "k"); the output is call to slog.Logger.Info missing a final value.
Common misconceptions
| Belief | Reality |
|---|---|
"os.Getenv errors when the variable is missing" | It returns ""; use os.LookupEnv to tell unset from empty |
"log.Fatal shuts down cleanly" | It calls os.Exit(1); deferred functions never run |
"flag.Parse() handles flags anywhere on the line" | It stops at the first non-flag argument; later flags stay in Args() |
"A boolean flag takes -v false" | Only -v=false; -v false makes false a positional argument |
| "Structured logging means JSON" | It means attributes stay separate from the message until formatting; text is structured too |
"logger.With changes the logger" | It returns a new logger; the old one is unchanged |
"My wrapper handler is fine without WithAttrs" | Without re-wrapping, the wrapper vanishes on the first With |
| "Putting the token in a flag is fine" | Command lines are visible in ps and shell history |
"slog writes to stdout by default" | The default logger writes through log, which uses stderr |
| "Libraries should log their errors" | Libraries return errors and take an injected logger |
| "Exit code 1 is the only failure code" | Use 2 for usage errors and document more |
".env should override real environment variables" | The real environment must win; godotenv.Load does not override |
Cheat sheet
| Topic | What to remember |
|---|---|
| Flag syntax | -x, --x, -x=v, -x v; booleans only as -x or -x=false |
| Parsing stops | at the first non-flag argument or at -- |
| Testable parsing | flag.NewFlagSet(name, flag.ContinueOnError), SetOutput, Parse(args) |
| Help | -h returns flag.ErrHelp; exit 0 |
| Custom types | Var with String/Set; TextVar for UnmarshalText types |
| Subcommands | switch on args[0], one FlagSet each, return an int |
| Env | LookupEnv for presence; Getenv cannot tell empty from unset |
| Precedence | defaults, file, env, flags; pass lower layer as the default of the next |
| Exit | os.Exit(run()) once; 0 ok, 1 fail, 2 usage |
| Streams | data to stdout, logs/errors/usage-after-error to stderr |
| slog setup | slog.New(NewJSONHandler(os.Stderr, opts)), SetDefault once |
| Levels | Debug -4, Info 0, Warn 4, Error 8; LevelVar to change live |
| Wrapper handlers | override Handle, re-wrap in WithAttrs and WithGroup, run slogtest |
| Redaction | Secret type with LogValue plus a ReplaceAttr key list |
| Libraries | injected logger, slog.DiscardHandler default |
| TTY | x/term.IsTerminal per stream; honour NO_COLOR |
| Tests | Run(args, env, out, err) int and testscript |
| Shipping | go install ...@version, -ldflags -X, GoReleaser for matrices |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the difference between os.Getenv and os.LookupEnv, and which one detects APP_ADDR=? Must-know
Answer
Answer: Getenv returns the value or "" and cannot say whether the variable exists. LookupEnv returns (value, present), so APP_ADDR= yields ("", true) while an unset variable yields ("", false).
2 — Why should a testable CLI use its own FlagSet with ContinueOnError instead of the global flag.Parse? Important
Answer
Answer: The global set uses ExitOnError, which calls os.Exit(2) inside the library on a bad flag. A private set returns the error, writes to a writer you chose, and lets the caller decide the exit status, so tests can assert on it.
3 — What does flag.Parse do with tool in.txt -v? Important
Answer
Answer: It stops at in.txt, the first non-flag argument, so -v stays in Args() as a positional argument and the verbose flag is not set.
4 — Why does log.Fatal skip deferred functions? Must-know
Answer
Answer: It writes the message and then calls os.Exit(1), which terminates the process immediately without unwinding the stack, so no defer runs and buffers are not flushed.
5 — Which exit code do you return for tool -nope, which for a failed network call, and which for -h? Important
Answer
Answer: 2 for the usage error (the convention the flag package itself follows), 1 for the failed operation, and 0 for -h because the user asked for help.
6 — Where do results, logs and usage text go? Must-know
Answer
Answer: Results to stdout. Logs, progress and error messages to stderr. Usage after a mistake goes to stderr; usage requested with -h or help may go to stdout.
7 — What must a wrapper slog.Handler do in WithAttrs and WithGroup? Good to know
Answer
Answer: Call the inner handler's method and return a new wrapper around the result. Returning the inner handler drops the wrapper's behaviour as soon as someone calls logger.With.
8 — How does slog avoid computing an expensive attribute when the level is disabled? Important
Answer
Answer: The logger asks handler.Enabled(ctx, level) first and returns early. A slog.LogValuer is only evaluated when the record is handled, so a disabled Info line never calls LogValue.
9 — How do you keep a token out of logs even when someone logs the whole config struct? Important
Answer
Answer: Give the field a type implementing slog.LogValuer (and String/MarshalText) that returns [REDACTED], and add a ReplaceAttr key list as a second layer.
10 — How does the precedence trick avoid special code in the flag layer? Important
Answer
Answer: Load defaults, then file, then env into the config struct, and register each flag with that struct field as its default. A flag not given keeps the lower layer's value; a flag given overwrites it.
11 — What should a library do instead of calling log.Printf? Must-know
Answer
Answer: Return errors, accept an optional *slog.Logger, and default to slog.New(slog.DiscardHandler) so it is silent unless the application opts in.
12 — Why detect a terminal per stream? Good to know
Answer
Answer: Stdout and stderr can be redirected independently. Progress belongs on stderr, so ask whether stderr is a terminal; data formatting depends on stdout.
Glossary
| Term | Definition |
|---|---|
os.Args | slice of command-line strings; index 0 is the program name |
flag | standard-library package that parses command-line flags |
FlagSet | a named set of flags with its own parsing, usage and error handling |
flag.Value | interface with String and Set that makes a custom flag type |
flag.Args | the arguments left after flag parsing stopped |
flag.ErrHelp | error returned when -h or -help is seen |
ContinueOnError | FlagSet mode that returns the parse error to the caller |
| usage | the help text printed by -h or after a flag error |
| subcommand | a verb (greet) selecting a command with its own flags |
cobra | CLI framework with command trees, persistent flags, completion and docs |
urfave/cli | declarative CLI framework with env lookup and completion |
kong | CLI parser that maps struct tags to commands and flags |
os.Getenv | returns an environment variable or "" |
os.LookupEnv | returns the value and whether the variable is set |
os.Environ | copy of the whole environment as key=value strings |
| 12-factor | methodology whose factor III stores configuration in the environment |
| configuration precedence | the order in which sources override each other |
.env | local file of KEY=value lines loaded by tools such as godotenv |
godotenv | library that loads a .env file without overriding the real environment |
envconfig | library that fills a struct from prefixed environment variables |
koanf | library that merges configuration from several providers |
viper | configuration library with files, env, flags and remote sources |
| exit code | integer status a process returns to its caller |
os.Exit | terminates immediately, skipping deferred calls |
| stdout | file descriptor 1; the program's results |
| stderr | file descriptor 2; logs, errors, progress |
log | the original standard logger with no levels or fields |
log.Fatal | print then os.Exit(1) |
log/slog | structured logging package added in Go 1.21 |
Logger | the value you call to emit records |
Handler | interface that decides whether and how a record is written |
TextHandler | slog handler writing key=value lines |
JSONHandler | slog handler writing one JSON object per line |
Level | integer severity: Debug -4, Info 0, Warn 4, Error 8 |
Attr | a typed key-value pair attached to a record |
Group | a named set of attributes, printed g.key or nested |
slog.With | returns a logger with attributes pre-attached |
LogAttrs | allocation-lean logging call taking only Attr values |
slog.SetDefault | installs the default logger for slog and log |
ReplaceAttr | handler option that rewrites or drops attributes |
| custom handler | your own slog.Handler, often a wrapper |
| redaction | replacing sensitive values before they are written |
| trace id | identifier shared by every record of one request |
| correlation id | any id used to join records across components |
| structured logging | logging with attributes kept separate from the message |
| PII | personally identifiable information that must not be logged |
| sampling | keeping only a fraction of low-severity records |
| verbosity | the -v style switch that lowers the log threshold |
--json | flag that switches stdout to machine-readable output |
| TTY | an interactive terminal device |
x/term | golang.org/x/term, provides IsTerminal |
zap | Uber's fast structured logger |
zerolog | zero-allocation JSON logger with a chained API |
testscript | runs .txtar command scripts as Go tests |
goreleaser | tool that builds, archives and publishes release binaries |
artisan | Laravel's command-line interface |
| Symfony Console | PHP library underneath Artisan |
| Monolog | PHP logging library used by Laravel |
References
Read and saved while writing this page (documentation versions: Go 1.25 standard library source and release notes; module versions in the snippet go.mod).
- The Twelve-Factor App, III. Config (opening quote)
- Structured Logging with slog, Go blog (design rationale)
- Go 1.21 release notes, Go 1.24, Go 1.25
- flag source, Go 1.25
- log source, Go 1.25
- log/slog package documentation source, Go 1.25
- Effective Go and Go Code Review Comments
- testscript package source and go-internal
- golang.org/x/term source
- cobra user guide, cobra.dev
- urfave/cli, kong
- godotenv, envconfig, koanf, viper
- zap, zerolog
- GoReleaser quick start
- NO_COLOR
- Laravel 13 Artisan, Laravel 13 Logging
- Symfony Console component, Monolog