// Package logging configures anchorage's structured logger. // // The design mirrors the sibling kanrisha project: stdlib log/slog with a // fan-out handler that writes every record to both a rotating JSON file (all // levels ≥ configured level, for machine parsing) and stderr (warn+ only, // human-friendly format, for quick console checks). // // The logger is installed globally via slog.SetDefault so every package // can simply import "log/slog" and call slog.Info / slog.Error without // dependency wiring. package logging import ( "context" "fmt" "log/slog" "os" "strings" lumberjack "gopkg.in/natefinch/lumberjack.v2" ) // Config holds logging parameters, typically loaded from Viper. // // File is optional: when empty, the file handler is skipped and stderr // receives every record (useful for local dev and short-lived CLI commands). type Config struct { // Level is the minimum level for file output: "debug", "info", "warn", "error". // Empty string is treated as "info". Level string // Format controls stderr rendering: "json" or "text" (default). Format string // Source toggles source file:line attributes on every record. Source bool // File is the rotating log file path. Empty disables file logging. File string // MaxSizeMB is the rotation threshold in megabytes. Ignored when File is empty. MaxSizeMB int // MaxBackups caps the number of rotated files retained. MaxBackups int // MaxAgeDays caps the age (in days) of rotated files before deletion. MaxAgeDays int // Compress gzips rotated files when true. Compress bool } // Init installs the process-wide slog.Default handler. // // Call once, after config has been loaded and before any subsystem startup // so that everything that fires off goroutines sees the correct logger. func Init(cfg Config) error { fileLevel, err := parseLevel(cfg.Level) if err != nil { return fmt.Errorf("logging level: %w", err) } stderrFormat := strings.ToLower(cfg.Format) if stderrFormat != "" && stderrFormat != "json" && stderrFormat != "text" { return fmt.Errorf("unknown log format %q — must be json or text", cfg.Format) } handlers := make([]slog.Handler, 0, 2) // File handler: always JSON, respects configured level. if cfg.File != "" { fileWriter := &lumberjack.Logger{ Filename: cfg.File, MaxSize: cfg.MaxSizeMB, MaxBackups: cfg.MaxBackups, MaxAge: cfg.MaxAgeDays, Compress: cfg.Compress, } handlers = append(handlers, slog.NewJSONHandler(fileWriter, &slog.HandlerOptions{ Level: fileLevel, AddSource: cfg.Source, })) } // Stderr handler. When the file handler is present, stderr is noisy-only // (warn+). Without a file handler, stderr must carry every record. stderrLevel := slog.LevelWarn if cfg.File == "" { stderrLevel = fileLevel } stderrOpts := &slog.HandlerOptions{ Level: stderrLevel, AddSource: cfg.Source, } var stderrHandler slog.Handler switch stderrFormat { case "json": stderrHandler = slog.NewJSONHandler(os.Stderr, stderrOpts) default: // "text" or "" stderrHandler = slog.NewTextHandler(os.Stderr, stderrOpts) } handlers = append(handlers, stderrHandler) slog.SetDefault(slog.New(&fanoutHandler{handlers: handlers})) slog.Debug("logging initialized") return nil } // fanoutHandler dispatches each record to multiple slog.Handlers. // // Mirrors kanrisha's implementation: clones the record per handler so state // (attrs, groups) does not leak between outputs. type fanoutHandler struct { handlers []slog.Handler attrs []slog.Attr groups []string } // Enabled reports whether at least one child handler would accept the level. func (h *fanoutHandler) Enabled(_ context.Context, level slog.Level) bool { for _, handler := range h.handlers { if handler.Enabled(context.Background(), level) { return true } } return false } // Handle forwards the record to every child handler that accepts its level. func (h *fanoutHandler) Handle(ctx context.Context, r slog.Record) error { for _, handler := range h.handlers { if handler.Enabled(ctx, r.Level) { if err := handler.Handle(ctx, r.Clone()); err != nil { return err } } } return nil } // WithAttrs returns a fresh fanoutHandler that applies the attrs to each child. func (h *fanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler { newHandlers := make([]slog.Handler, len(h.handlers)) for i, handler := range h.handlers { newHandlers[i] = handler.WithAttrs(attrs) } return &fanoutHandler{ handlers: newHandlers, attrs: append(h.attrs, attrs...), groups: h.groups, } } // WithGroup returns a fresh fanoutHandler that applies the group to each child. func (h *fanoutHandler) WithGroup(name string) slog.Handler { newHandlers := make([]slog.Handler, len(h.handlers)) for i, handler := range h.handlers { newHandlers[i] = handler.WithGroup(name) } return &fanoutHandler{ handlers: newHandlers, attrs: h.attrs, groups: append(h.groups, name), } } // parseLevel converts a config string to slog.Level. // // Empty string and "info" both map to LevelInfo so zero-valued Configs are // ergonomic. Unknown values return an error (and LevelInfo as a safe default // in case the caller logs the error and carries on). func parseLevel(s string) (slog.Level, error) { switch strings.ToLower(s) { case "debug": return slog.LevelDebug, nil case "info", "": return slog.LevelInfo, nil case "warn", "warning": return slog.LevelWarn, nil case "error": return slog.LevelError, nil default: return slog.LevelInfo, fmt.Errorf("unknown log level %q — must be debug, info, warn, or error", s) } }