Go - Logging & Configuration
Beginner 10/10
Teacher 10/10
Architect 10/10
Logging & Configuration
Start simple with standard library logging, then adopt structured logging and layered configuration (env, flags, files).
Try it: Read a port from env with a default and log a startup message.
log package
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Println("starting server")
Structured logging (slog)
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("started", "port", 8080, "env", "dev")
Configuration layers
type Config struct{ Port int; Env string }
func Load() Config{
c := Config{Port:8080, Env:"dev"}
if v := os.Getenv("PORT"); v != "" { if p, _ := strconv.Atoi(v); p>0 { c.Port = p } }
if v := os.Getenv("ENV"); v != "" { c.Env = v }
return c
}
Common errors
- Logging secrets or PII. Redact sensitive fields.
- Inconsistent log formats across services—standardize early.
Practice
- Add a
--port
flag that overrides environment variables.
Quick quiz
- Why prefer structured logs?