Skip to content

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 forGo to
A one-minute table of the whole chapterEverything in one minute
Why a CLI has more than one input and outputWhy it exists
History: flag, 12-factor, log/slogWhere it comes from
flag.Parse, flag.Args, types, -h, --The flag package
Custom flag.Value, TextVar, flag.FuncCustom flag types
FlagSet per subcommand, os.Args[1]Subcommands
cobra, urfave/cli, kong comparedCLI frameworks
os.Getenv, os.LookupEnv, os.Environ, .envEnvironment variables
flags over env over fileConfiguration precedence
os.Exit, exit codes, log.FatalExit codes
stdout for data, stderr for logs, stdinStandard streams
log package and its limitsThe log package
Logger, Handler, levels, attributes, groupslog/slog basics
slog.With, LogAttrs, context, SetDefaultLoggers in practice
ReplaceAttr, redaction, custom handlers, trace idHandlers you write
keys, PII, sampling, correlation idsStructured logging practice
libraries versus applicationsLogging in libraries
zap and zerologThird-party loggers
-v, --json, TTY, x/term, NO_COLORVerbosity, JSON and TTY
testscript, capturing stdoutTesting a CLI
go install, -ldflags -X, GoReleaserShipping a CLI
Exact error texts and level numbersMechanics
Fixes for classic mistakesSolving the classic problems
Which tool for which jobChoosing
Artisan, Symfony Console, MonologFor PHP/Laravel developers
From one binary to a fleetIn architecture
Run it yourselfLab

Everything in one minute ​

ChannelStandard-library toolWhat to remember
Argumentsflag-x, --x, -x=v; stops at the first non-flag; -- ends flags
Subcommandsone flag.FlagSet per command, switch on os.Args[1]Parse args[1:] with the command's own set
Environmentos.LookupEnvUnset and empty are different; os.Getenv hides the difference
Precedencedefaults, then file, then env, then flagsFeed each layer in as the default of the next
Exit statusos.Exit(code) once, in main0 success, 1 failure, 2 usage error; deferred calls do not run
Dataos.StdoutOnly results; safe to pipe
Diagnosticsos.StderrLogs, progress, errors, usage text
Logginglog/slog since Go 1.21Levels, attributes, groups, handlers; one logger injected, not global
Secretsslog.LogValuer, ReplaceAttrRedact in the logger, not at each call site
TestsRun(args, env, stdout, stderr) int and testscriptMake main a one-liner
LevelNumberMeaningDefault handler
slog.LevelDebug-4developer detailhidden
slog.LevelInfo0normal eventsshown (default threshold)
slog.LevelWarn4recoverable surpriseshown
slog.LevelError8operation failedshown
HandlerOutputWhen
slog.NewTextHandlertime=... level=INFO msg=... k=vterminals, local development
slog.NewJSONHandlerone JSON object per linelog pipelines, containers
slog.DiscardHandler (Go 1.24)nothinglibrary default, tests
custom slog.Handleranythingredaction, 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-offSimplerRicher
Flag parsingflag from the standard library: no dependency, tiny binarycobra/kong: nested commands, completion, generated docs
Configurationflags and env onlyfile layer, hot reload, remote sources (viper, koanf)
Logginglog.Printf: one stringlog/slog: record with level, time, attributes, pluggable handler
Loggerpackage-level globalinjected *slog.Logger: testable, per-request attributes
Outputtext 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 ​

  1. "os.Getenv returns an error when a variable is missing." It returns the empty string, the same as a variable that is set to nothing. Only os.LookupEnv tells them apart.
  2. "log.Fatal is a convenient way to exit with an error." It writes and calls os.Exit(1) immediately: deferred functions do not run, files are not flushed, and no caller can recover.
  3. "Structured logging means JSON." JSON is one encoding. Structured means the message and the attributes are separate values until the handler formats them; TextHandler is structured too.

Where it comes from ​

  • Unix argv/environ/streams. The contract predates Go by decades; Go exposes it as os.Args, os.Environ and os.Stdin/Stdout/Stderr. The flag package 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/slog arrived 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 added slog.DiscardHandler; Go 1.25 added slog.GroupAttrs and Record.Source.
  • testscript grew out of the script tests of the Go command itself (its documentation still says to run one with go test cmd/go -run=TestName/^foo$) and is packaged in github.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.

text
 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.

ConstructorGo typeParse failure text (from the test)
fs.String / StringVarstringnever fails
fs.Int / IntVarintinvalid value "x" for flag -workers: parse error
fs.Bool / BoolVarboolinvalid boolean value "maybe" for -v: parse error
fs.Duration / DurationVartime.Durationinvalid value "soon" for flag -timeout: parse error
fs.Float64, Uint, Int64, Uint64numericsame shape as Int
fs.Var(value, ...)any flag.Valuewhatever Set returns
fs.TextVar(p, ...) (Go 1.19)encoding.TextUnmarshalerUnmarshalText error, wrapped
fs.Func(name, usage, fn) (Go 1.16)callback per occurrencethe callback's error
fs.BoolFunc (Go 1.21)callback, no valuethe 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.

go
// 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.

text
 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
NeedUseWhy
A repeatable flagcustom Value that appendsSet runs per occurrence
A comma-separated listcustom Value that splitsone occurrence, many items
An enum (text/json)Func or custom Value that validatesreject early with a clear error
A type that already has UnmarshalText (slog.Level, net/netip.Addr, time.Time)TextVarno new type needed
A verb flag (-version)BoolFuncrun 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.

text
 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 0
os.Argstool greet -name Ada --json[0]=tool [1]=greet ...Run(args)switch args[0]greetFlagSet "tool greet"-name -jsonlogFlagSet "tool log"-format -v -no-timeversionno flagsexit code0 / 1 / 2unknown command: usage on stderr, exit 2-h on a command: usage, exit 0flags before the command name are not supported

The 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)).

go
// 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
}
go
// 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))
}
BehaviourWhere it lives in the snippet
tool with no arguments prints usage to stderr, exit 2Run, len(args) == 0
unknown command: usage to stderr, exit 2, stdout emptyRun, default branch
tool greet -h prints usage, exit 0parse, flag.ErrHelp
tool help and tool version print to stdout, exit 0Run
extra positional argument: exit 2runGreet, 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.

Aspectflag (stdlib)spf13/cobraurfave/clialecthomas/kong
Styleimperativecommands as *cobra.Command valuesdeclarative structs/slicesstruct tags on a Go struct
Subcommandshand-rolled with FlagSetbuilt in, nestedbuilt in, nestednested structs
Flag syntax-x and --xPOSIX via pflag: -x, --xx, grouped -abc-x, --xx, grouped short flags--xx, -x
Persistent (inherited) flagsnoyes, PersistentFlags()yesyes (parent struct fields)
Shell completionnonebash, zsh, fish, PowerShellbash, zsh, fish, PowerShellvia plugin
Env var bindingmanualmanual or viperbuilt in (EnvVars)env:"NAME" tag
Generated docsnoneman pages, Markdown, YAMLman and Markdown (cli-docs)help only
Typical usesmall tools, go:generateKubernetes, Hugo, GitHub CLImany mid-size toolstools that prefer structs
Costnonecobra, pflag, mousetrapno dependencies except the standard libraryone 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).

go
// 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, "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.

text
 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 variablesTypical useRisk
shell exportlocal developmentlost on the next shell
.env file loaded by joho/godotenvlocal development onlyaccidentally committed; never override real env
Kubernetes env: / envFrom:deployment configvisible to anyone who can kubectl describe
Kubernetes Secret mounted as envcredentialsvisible in /proc/<pid>/environ to the same user
mounted file (/run/secrets/token)credentialsneeds a file path flag or env var pointing at it
systemd Environment=/EnvironmentFile=services on hostsfile 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.

text
 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
1. Defaultscompiled into the binaryConfig{Addr: ":8080"}2. Config fileJSON / YAML / TOML--config path3. Environmentos.LookupEnv("APP_ADDR")set vs empty vs unset4. Flagsflag.Parse(args)explicit, per invocationLater layers win; each layer becomes the default shown by the next one (flag -h prints the merged value)Config struct (typed, validated once, secrets as logx.Secret)Secrets: env or file,never a flag (ps, history)
SourceWins overLoses toGood for
compiled-in defaultnothingeverythingsafe local run
config filedefaultsenv, flagsmany settings, versioned per environment
environmentfileflagsper-deploy values, secrets
flageverythingnothingone-off override by the operator
go
// 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.

CodeConvention hereSource
0success (and -h)everywhere
1the operation failed (I/O, network, bad data)log.Fatal uses 1; project convention
2usage error: unknown flag, bad argumentthe flag package's own ExitOnError choice, and Go panics
126, 127shell: not executable, command not foundthe shell, not your program
128+Nkilled by signal N (130 is Ctrl+C, 137 is SIGKILL)the shell reports it for you
3-125your own documented codes (for example 3 "nothing to do")document them in --help
go
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.

stdinfd 0pipe or filetool processflag.ParseRun(args) intos.Exit(code) oncestdout (fd 1): resultstext or --json, safe to pipestderr (fd 2): logs, progress, errorsslog handlers write hereexit status0 ok, 1 failure, 2 usage errortool greet --json | jq .greeting (stdout feeds jq)tool log 2> app.log (stderr to a file)tool x || echo "exit $?" (status to the shell)
OutputStreamReason
results (--json, lists, generated code)stdoutconsumed by pipes and files
usage text after a mistakestderrnot part of the result
usage text after -h or helpstdoutthe user asked for it; tool -h | less works
error messagesstderrwith a non-zero exit status
logs and progressstderrkeep stdout machine-clean
prompts for inputstderr (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.

go
// 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).

text
 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"}}
Loggerlogger.InfoContext(ctx, msg, attrs...)Recordtime, level, msg,attrs, pcContextHandleradds trace_idfrom ctxSamplerdrops 9 of 10below WarnTextHandlerkey=value linesJSONHandlerone JSON object per lineReplaceAttr: redact password, token; drop timeEnabled(ctx, level) is asked first: a disabled level costs one comparisonOutput: os.Stderr(io.Writer)
ConceptType / functionBehaviour
Level thresholdHandlerOptions.Level (a slog.Leveler)default Info; use *slog.LevelVar to change at runtime
Timebuilt-in key timeremoved by returning an empty Attr from ReplaceAttr
Messagebuilt-in key msga user attribute named msg duplicates it; avoid
SourceHandlerOptions.AddSourceadds source (function, file, line); costs a stack lookup
Groupslog.Group("req", ...) or logger.WithGroup("req")text prints req.method, JSON nests them under a req object
Default loggerslog.Default()writes through the log package's default output
Discardslog.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.

go
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
StyleAllocationsType safetyWhen
logger.Info("m", "k", v)boxes v into anynone: odd count caught by vet onlyeveryday code
logger.Info("m", slog.Int("k", n))no boxing for scalarstypednormal
logger.LogAttrs(ctx, lvl, "m", attrs...)lowesttypedhot paths
slog.Any("k", v)boxes vnonestructs, errors, maps
slog.LogValuer on a typeevaluated only if the level is enabledtypedexpensive 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).

text
 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"}
TechniqueWhere it actsStrengthWeakness
ReplaceAttr key listevery attribute, any depthcatches mistakes at the call siteonly keys you listed; a value inside a message string is untouched
slog.LogValuer on Secretthe typesecret can never print, even via %v and JSONdevelopers must use the type
ContextHandlerper recordtrace id on every line without passing it everywhereneeds InfoContext; plain Info has no ctx
Samplerper recordcaps volume of Info/Debugdrops are invisible; counters are per process
MultiHandler-style fan-outper recordtext to stderr and JSON to a fileyou must handle one destination failing
go
// 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 }
go
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.

RuleDoAvoid
Messageconstant text: "payment failed"interpolated: "payment 8812 failed" (cannot group by message)
Keyssnake_case, same everywhere: user_id, order_id, duration_msuserId in one file and uid in another
Unitsslog.Duration or a unit in the key"took": 1.5
Errorsslog.Any("err", err) or key errorerr.Error() pasted into the message
PIIids and hashed valuese-mail, phone, token, card number, request bodies
SecretsSecret type and ReplaceAttrtrusting reviewers to notice
LevelError = needs action; Warn = degraded; Info = business events; Debug = developereverything at Info
Correlationone request_id or W3C trace_id on every recordone 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.

go
// 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()
}
ConcernApplicationLibrary
Chooses handler, level, destinationyesno
Calls slog.SetDefaultonce, in mainnever
Uses package-level slog.Infoacceptable in small toolsavoid; take a logger
On failurelog once at the top, exitreturn an error, optionally log Debug detail
Adds component attributeoptionalyes, 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.

Aspectlog/sloggo.uber.org/zapgithub.com/rs/zerolog
In the standard libraryyesnono
API styleInfo(msg, kv...), LogAttrszap.Logger typed fields, SugaredLoggerchained builder log.Info().Str("k","v").Msg("m")
Allocationslow with LogAttrsvery low (typed fields)"Zero Allocation JSON Logger"
Pluggable backendslog.Handler interfacehas an slog handler bridgehas an slog handler bridge
Levelsintegers, extensiblefixed enum plus dynamic AtomicLevelfixed enum
Choose whendefault for new codehot paths, existing zap codebaseJSON-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.

go
// 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)
	}
}
text
 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"
FlagConventionEffect in the snippets
-v, --verboserepeatable in many toolstool log -v lowers the level to Debug
-q, --quietsuppress non-error outputnot implemented; add as slog.LevelError
--jsonmachine-readable data on stdouttool greet --json
--log-format jsonmachine-readable logs on stderrtool log -format json
--no-color / NO_COLORdisable ANSI colourttyout.ColorEnabled
--versionprint version, exit 0tool 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.

go
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"})
}
txtar
# 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:'
LevelToolWhat it provesSpeed
Parse functionParse(args, &stderr) in a table testflags, defaults, error textsmicroseconds
Command functionRun(args, env, &out, &err)output, streams, exit codemicroseconds
Real binarytestscript with exec toolthe actual main, pipes, filestens of ms
Cobracmd.SetArgs, SetOut, SetErr, Execute()the same, via the frameworkmicroseconds
Handlerstesting/slogtest.TestHandlera custom Handler honours the contractmicroseconds
Env in testst.Setenvrestores the variable automaticallyn/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.

StepCommandNote
Install from sourcego install example.com/me/tool/cmd/tool@v1.2.3needs a Go toolchain
Embed the versiongo build -ldflags "-X academy/cli-flags-env-logging/subcmd.Version=v1.2.3"sets a string variable at link time
Read build inforuntime/debug.ReadBuildInfo()module version and VCS stamp without -ldflags
Cross-compileGOOS=linux GOARCH=arm64 go buildno extra toolchain needed
Release many targetsgoreleaser releasearchives, checksums, Homebrew taps, GitHub release (GoReleaser quick start)
Static binaryCGO_ENABLED=0 go buildideal 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.

SituationText or value
unknown flagflag provided but not defined: -nope
flag without its valueflag needs an argument: -addr
bad integerinvalid value "x" for flag -workers: parse error
custom Set rejectsinvalid value " " for flag -tag: empty value
-h under ContinueOnErrorParse returns flag: help requested (flag.ErrHelp)
defining a flag twicepanic: flag redefined: addr
flag.CommandLine after a bad flagusage 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 textslog: level string "loud": unknown name
cobra: too many argumentsaccepts at most 1 arg(s), received 2
cobra: unknown flagunknown flag: --loud
cobra: unknown commandunknown command "nope" for "app"
env set but emptyAPP_ADDR is set but empty (our rule, not the runtime's)
bad bool in envAPP_DEBUG: strconv.ParseBool: parsing "maybe": invalid syntax
bad duration in envAPP_TIMEOUT: time: invalid duration "soon"

Every knob of HandlerOptions, Logger and flag Important ​

KnobTypeDefaultEffect
HandlerOptions.Levelslog.LevelerInfominimum level; pass *slog.LevelVar for runtime changes
HandlerOptions.AddSourceboolfalseadds file and line of the call site
HandlerOptions.ReplaceAttrfunc([]string, Attr) Attrnilrewrite, rename or drop attributes
slog.SetLogLoggerLevelfunc(Level) LevelInfolevel assigned to legacy log calls routed through slog
flag.ContinueOnErrorErrorHandlingn/areturn the error
flag.ExitOnErrorErrorHandlingthe global set's modeprint usage, os.Exit(2) (-h: 0)
flag.PanicOnErrorErrorHandlingn/apanic with the error
FlagSet.Usagefunc()prints defaultsyour own help text
FlagSet.SetOutputio.Writerstderrwhere usage and errors go
log.SetFlagsintLstdFlagsdate, time, file, microseconds
log.SetOutputio.Writerstderrdestination 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.

TextLevelNote
debug-4
info0
warn4
error8
info+22between Info and Warn
debug-4-8what LevelTrace prints without renaming

Solving the classic problems ​

ProblemSolutionHowCost or limitation
Typo in a flag kills a test runown FlagSet with ContinueOnErrorParse(args, &stderr) returns the errora few more lines
Secret in ps outputread from env or fileno flag for itfile permissions matter
Secret in logsSecret type with LogValue, ReplaceAttr listredaction in the loggerdefence in depth, not proof
Defers skippedos.Exit(run())exit once in mainone extra function
Logs corrupt a pipelogs to stderr, data to stdoutexplicit writersnone
Can't tell unset from emptyLookupEnvtreat "set but empty" explicitlyone more branch
Different config per environmentlayered precedencedefaults, file, env, flagsdocument the order
Global flags before subcommandpersistent flags in cobra or repeat in each setframeworkdependency
No trace id in logsContextHandleradd from ctxcallers must pass ctx
Log volume explosionlevel discipline plus Samplerdrop Info/Debug 9 of 10drops invisible
Library prints to stdoutinjected logger, discard defaultWithLoggerone option
Unreadable JSON in a terminalTTY detectiontext on TTY, JSON otherwisetwo formats to test
Slow go vet surprisesrun go vetcatches odd slog key listsnone

Replace log.Fatal in an application ​

go
// 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 ​

go
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 ​

SituationChooseReason
One binary, one purpose, a handful of flagsflagno dependency
Several subcommands, little nestingFlagSet per commandclear, testable
Deep command tree, completion, docscobra (or kong for struct style)built in
Declarative style with env bindingurfave/clienv and files in the definition
Containerised serviceenv vars plus flags12-factor
Many settings, files, hot reloadkoanf or vipermultiple providers
Local development secrets.env via godotenvconvenience only
New service logginglog/slog JSON to stderr/stdoutstandard, pluggable
Interactive tool loggingslog text handler to stderrreadable
Hot-path logging, measuredzap or zerolog behind slogallocations
Libraryaccept *slog.Logger, discard by defaultguest behaviour
Test the real binarytestscriptscripts 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):

sql
-- 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 ​

ScaleLoggingConfigurationCLI
1x: one hosttext to stderr, journalctl or a fileflags and envflag and FlagSet
10x: a few servicesJSON, shipped by an agent, trace_id everywhereshared config package, env from the orchestratorshared internal CLI conventions, cobra if commands grow
100x: many teamssampling in the pipeline, retention tiers, PII scrubbing as a gatetyped schema per service, central secrets managergoreleaser 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.

ConcernLaravel / PHPGo
Command definitionArtisan $signature or Symfony configure()FlagSet or cobra.Command
Help textgenerated-h prints PrintDefaults; cobra generates more
Exit statusreturn Command::SUCCESS / FAILUREos.Exit(code) once in main
Output streams$this->line() to stdout, $this->error() to stderros.Stdout, os.Stderr
Config.env, config()os.LookupEnv, struct, precedence
LoggingLog::info('msg', ['id' => 1]) via Monologlogger.Info("msg", "id", 1) via slog
Per-request contextLog::withContext([...])logger.With(...) or a ContextHandler
Log channels (stack, daily, stderr)config/logging.phpone handler, or a fan-out handler
Deploymentphp artisan inside the appa static binary per tool
php
// 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).

bash
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 2

Observed usage text (exit status 2 after the error line):

text
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.

bash
/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.

bash
/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.

bash
gofmt -l .          # no output
go vet ./...        # no output
go test -race ./... # ok for flagset, subcmd, envcfg, logx, widget, ttyout, cobraapp, cmd/tool

Experiment 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 ​

BeliefReality
"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 ​

TopicWhat to remember
Flag syntax-x, --x, -x=v, -x v; booleans only as -x or -x=false
Parsing stopsat the first non-flag argument or at --
Testable parsingflag.NewFlagSet(name, flag.ContinueOnError), SetOutput, Parse(args)
Help-h returns flag.ErrHelp; exit 0
Custom typesVar with String/Set; TextVar for UnmarshalText types
Subcommandsswitch on args[0], one FlagSet each, return an int
EnvLookupEnv for presence; Getenv cannot tell empty from unset
Precedencedefaults, file, env, flags; pass lower layer as the default of the next
Exitos.Exit(run()) once; 0 ok, 1 fail, 2 usage
Streamsdata to stdout, logs/errors/usage-after-error to stderr
slog setupslog.New(NewJSONHandler(os.Stderr, opts)), SetDefault once
LevelsDebug -4, Info 0, Warn 4, Error 8; LevelVar to change live
Wrapper handlersoverride Handle, re-wrap in WithAttrs and WithGroup, run slogtest
RedactionSecret type with LogValue plus a ReplaceAttr key list
Librariesinjected logger, slog.DiscardHandler default
TTYx/term.IsTerminal per stream; honour NO_COLOR
TestsRun(args, env, out, err) int and testscript
Shippinggo install ...@version, -ldflags -X, GoReleaser for matrices

Self-check: questions & answers ​

Show:
  • 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 ​

TermDefinition
os.Argsslice of command-line strings; index 0 is the program name
flagstandard-library package that parses command-line flags
FlagSeta named set of flags with its own parsing, usage and error handling
flag.Valueinterface with String and Set that makes a custom flag type
flag.Argsthe arguments left after flag parsing stopped
flag.ErrHelperror returned when -h or -help is seen
ContinueOnErrorFlagSet mode that returns the parse error to the caller
usagethe help text printed by -h or after a flag error
subcommanda verb (greet) selecting a command with its own flags
cobraCLI framework with command trees, persistent flags, completion and docs
urfave/clideclarative CLI framework with env lookup and completion
kongCLI parser that maps struct tags to commands and flags
os.Getenvreturns an environment variable or ""
os.LookupEnvreturns the value and whether the variable is set
os.Environcopy of the whole environment as key=value strings
12-factormethodology whose factor III stores configuration in the environment
configuration precedencethe order in which sources override each other
.envlocal file of KEY=value lines loaded by tools such as godotenv
godotenvlibrary that loads a .env file without overriding the real environment
envconfiglibrary that fills a struct from prefixed environment variables
koanflibrary that merges configuration from several providers
viperconfiguration library with files, env, flags and remote sources
exit codeinteger status a process returns to its caller
os.Exitterminates immediately, skipping deferred calls
stdoutfile descriptor 1; the program's results
stderrfile descriptor 2; logs, errors, progress
logthe original standard logger with no levels or fields
log.Fatalprint then os.Exit(1)
log/slogstructured logging package added in Go 1.21
Loggerthe value you call to emit records
Handlerinterface that decides whether and how a record is written
TextHandlerslog handler writing key=value lines
JSONHandlerslog handler writing one JSON object per line
Levelinteger severity: Debug -4, Info 0, Warn 4, Error 8
Attra typed key-value pair attached to a record
Groupa named set of attributes, printed g.key or nested
slog.Withreturns a logger with attributes pre-attached
LogAttrsallocation-lean logging call taking only Attr values
slog.SetDefaultinstalls the default logger for slog and log
ReplaceAttrhandler option that rewrites or drops attributes
custom handleryour own slog.Handler, often a wrapper
redactionreplacing sensitive values before they are written
trace ididentifier shared by every record of one request
correlation idany id used to join records across components
structured logginglogging with attributes kept separate from the message
PIIpersonally identifiable information that must not be logged
samplingkeeping only a fraction of low-severity records
verbositythe -v style switch that lowers the log threshold
--jsonflag that switches stdout to machine-readable output
TTYan interactive terminal device
x/termgolang.org/x/term, provides IsTerminal
zapUber's fast structured logger
zerologzero-allocation JSON logger with a chained API
testscriptruns .txtar command scripts as Go tests
goreleasertool that builds, archives and publishes release binaries
artisanLaravel's command-line interface
Symfony ConsolePHP library underneath Artisan
MonologPHP 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).

Built by Morteza Negahi