| 1 | // Package slag provides a method for setting the log level from the command line. |
| 2 | // |
| 3 | // func main() { |
| 4 | // var level slag.Level |
| 5 | // flag.Var(&level, "log-level", "log level") |
| 6 | // flag.Parse() |
| 7 | // slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: &level}))) |
| 8 | // } |
| 9 | // |
| 10 | // See [./examples/logger](./examples/logger) for a full example. |
| 11 | // |
| 12 | // This allows the log level to be set from the command line: |
| 13 | // |
| 14 | // $ ./myprogram -log-level=debug |
| 15 | // |
| 16 | // The slag.Level type is a wrapper around slog.Level that implements the flag.Value interface, |
| 17 | // as well as Cobra's pflag.Value interface. |
| 18 | // |
| 19 | // func main() { |
| 20 | // var level slag.Level |
| 21 | // cmd := &cobra.Command{ |
| 22 | // Use: "myprogram", |
| 23 | // ... |
| 24 | // } |
| 25 | // cmd.PersistentFlags().Var(&level, "log-level", "log level") |
| 26 | // cmd.Execute() |
| 27 | // } |
| 28 | package slag |
| 29 | |
| 30 | import "log/slog" |
| 31 | |
| 32 | type Level slog.Level |
| 33 | |
| 34 | func (l *Level) Set(s string) error { |
| 35 | var ll slog.Level |
| 36 | if err := ll.UnmarshalText([]byte(s)); err != nil { |
| 37 | return err |
| 38 | } |
| 39 | *l = Level(ll) |
| 40 | return nil |
| 41 | } |
| 42 | func (l *Level) String() string { return slog.Level(*l).String() } |
| 43 | func (l *Level) Level() slog.Level { return slog.Level(*l) } |
| 44 | |
| 45 | // Implements https://pkg.go.dev/github.com/spf13/pflag#Value |
| 46 | func (l *Level) Type() string { return "string" } |