|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// SPDX-FileCopyrightText: 2021-Present The Zarf Authors |
| 3 | + |
| 4 | +// Package logger implements a log/slog based logger in Zarf. |
| 5 | +package logger |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "log/slog" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | + "sync/atomic" |
| 14 | +) |
| 15 | + |
| 16 | +var defaultLogger atomic.Pointer[slog.Logger] |
| 17 | + |
| 18 | +// init sets a logger with default config when the package is initialized. |
| 19 | +func init() { |
| 20 | + l, _ := New(ConfigDefault()) //nolint:errcheck |
| 21 | + SetDefault(l) |
| 22 | +} |
| 23 | + |
| 24 | +// Level declares each supported log level. These are 1:1 what log/slog supports by default. Info is the default level. |
| 25 | +type Level int |
| 26 | + |
| 27 | +// Store names for Levels |
| 28 | +var ( |
| 29 | + Debug = Level(slog.LevelDebug) // -4 |
| 30 | + Info = Level(slog.LevelInfo) // 0 |
| 31 | + Warn = Level(slog.LevelWarn) // 4 |
| 32 | + Error = Level(slog.LevelError) // 8 |
| 33 | +) |
| 34 | + |
| 35 | +// validLevels is a set that provides an ergonomic way to check if a level is a member of the set. |
| 36 | +var validLevels = map[Level]bool{ |
| 37 | + Debug: true, |
| 38 | + Info: true, |
| 39 | + Warn: true, |
| 40 | + Error: true, |
| 41 | +} |
| 42 | + |
| 43 | +// strLevels maps a string to its Level. |
| 44 | +var strLevels = map[string]Level{ |
| 45 | + "debug": Debug, |
| 46 | + "info": Info, |
| 47 | + "warn": Warn, |
| 48 | + "error": Error, |
| 49 | +} |
| 50 | + |
| 51 | +// ParseLevel takes a string representation of a Level, ensure it exists, and then converts it into a Level. |
| 52 | +func ParseLevel(s string) (Level, error) { |
| 53 | + k := strings.ToLower(s) |
| 54 | + l, ok := strLevels[k] |
| 55 | + if !ok { |
| 56 | + return 0, fmt.Errorf("invalid log level: %s", k) |
| 57 | + } |
| 58 | + return l, nil |
| 59 | +} |
| 60 | + |
| 61 | +// Format declares the kind of logging handler to use. An empty Format defaults to text. |
| 62 | +type Format string |
| 63 | + |
| 64 | +// ToLower takes a Format string and converts it to lowercase for case-agnostic validation. Users shouldn't have to care |
| 65 | +// about "json" vs. "JSON" for example - they should both work. |
| 66 | +func (f Format) ToLower() Format { |
| 67 | + return Format(strings.ToLower(string(f))) |
| 68 | +} |
| 69 | + |
| 70 | +// TODO(mkcp): Add dev format |
| 71 | +var ( |
| 72 | + // FormatText uses the standard slog TextHandler |
| 73 | + FormatText Format = "text" |
| 74 | + // FormatJSON uses the standard slog JSONHandler |
| 75 | + FormatJSON Format = "json" |
| 76 | + // FormatNone sends log writes to DestinationNone / io.Discard |
| 77 | + FormatNone Format = "none" |
| 78 | +) |
| 79 | + |
| 80 | +// More printers would be great, like dev format https://github.com/golang-cz/devslog |
| 81 | +// and a pretty console slog https://github.com/phsym/console-slog |
| 82 | + |
| 83 | +// Destination declares an io.Writer to send logs to. |
| 84 | +type Destination io.Writer |
| 85 | + |
| 86 | +var ( |
| 87 | + // DestinationDefault points to Stderr |
| 88 | + DestinationDefault Destination = os.Stderr |
| 89 | + // DestinationNone discards logs as they are received |
| 90 | + DestinationNone Destination = io.Discard |
| 91 | +) |
| 92 | + |
| 93 | +// Config is configuration for a logger. |
| 94 | +type Config struct { |
| 95 | + // Level sets the log level. An empty value corresponds to Info aka 0. |
| 96 | + Level |
| 97 | + Format |
| 98 | + Destination |
| 99 | +} |
| 100 | + |
| 101 | +// ConfigDefault returns a Config with defaults like Text formatting at Info level writing to Stderr. |
| 102 | +func ConfigDefault() Config { |
| 103 | + return Config{ |
| 104 | + Level: Info, |
| 105 | + Format: FormatText, |
| 106 | + Destination: DestinationDefault, // Stderr |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +// New takes a Config and returns a validated logger. |
| 111 | +func New(cfg Config) (*slog.Logger, error) { |
| 112 | + var handler slog.Handler |
| 113 | + opts := slog.HandlerOptions{} |
| 114 | + |
| 115 | + // Use default destination if none |
| 116 | + if cfg.Destination == nil { |
| 117 | + cfg.Destination = DestinationDefault |
| 118 | + } |
| 119 | + |
| 120 | + // Check that we have a valid log level. |
| 121 | + if !validLevels[cfg.Level] { |
| 122 | + return nil, fmt.Errorf("unsupported log level: %d", cfg.Level) |
| 123 | + } |
| 124 | + opts.Level = slog.Level(cfg.Level) |
| 125 | + |
| 126 | + switch cfg.Format.ToLower() { |
| 127 | + // Use Text handler if no format provided |
| 128 | + case "", FormatText: |
| 129 | + handler = slog.NewTextHandler(cfg.Destination, &opts) |
| 130 | + case FormatJSON: |
| 131 | + handler = slog.NewJSONHandler(cfg.Destination, &opts) |
| 132 | + // TODO(mkcp): Add dev format |
| 133 | + // case FormatDev: |
| 134 | + // handler = slog.NewTextHandler(DestinationNone, &slog.HandlerOptions{ |
| 135 | + // AddSource: true, |
| 136 | + // }) |
| 137 | + case FormatNone: |
| 138 | + handler = slog.NewTextHandler(DestinationNone, &slog.HandlerOptions{}) |
| 139 | + // Format not found, let's error out |
| 140 | + default: |
| 141 | + return nil, fmt.Errorf("unsupported log format: %s", cfg.Format) |
| 142 | + } |
| 143 | + |
| 144 | + log := slog.New(handler) |
| 145 | + return log, nil |
| 146 | +} |
| 147 | + |
| 148 | +// Default retrieves a logger from the package default. This is intended as a fallback when a logger cannot easily be |
| 149 | +// passed in as a dependency, like when developing a new function. Use it like you would use context.TODO(). |
| 150 | +func Default() *slog.Logger { |
| 151 | + return defaultLogger.Load() |
| 152 | +} |
| 153 | + |
| 154 | +// SetDefault takes a logger and atomically stores it as the package default. This is intended to be called when the |
| 155 | +// application starts to override the default config with application-specific config. See Default() for more usage |
| 156 | +// details. |
| 157 | +func SetDefault(l *slog.Logger) { |
| 158 | + defaultLogger.Store(l) |
| 159 | +} |
0 commit comments