logging.go48 lines, 1.3 KB
| 1 | // Package logging sets up structured logging with log/slog. |
| 2 | package logging |
| 3 | |
| 4 | import ( |
| 5 | "io" |
| 6 | "log/slog" |
| 7 | ) |
| 8 | |
| 9 | // Options configures a logger. |
| 10 | type Options struct { |
| 11 | Service string |
| 12 | Version string |
| 13 | Level slog.Level |
| 14 | Format string // "text" for humans, "json" for log collectors |
| 15 | } |
| 16 | |
| 17 | // New returns a logger that writes to w. Every line carries the service name |
| 18 | // and version, plus any attributes stored in the context with With. |
| 19 | func New(w io.Writer, o Options) *slog.Logger { |
| 20 | opts := &slog.HandlerOptions{Level: o.Level} |
| 21 | var h slog.Handler |
| 22 | if o.Format == "json" { |
| 23 | h = slog.NewJSONHandler(w, opts) |
| 24 | } else { |
| 25 | opts.ReplaceAttr = shortTime |
| 26 | h = slog.NewTextHandler(w, opts) |
| 27 | } |
| 28 | return slog.New(contextHandler{h}).With( |
| 29 | slog.String("service", o.Service), |
| 30 | slog.String("version", o.Version), |
| 31 | ) |
| 32 | } |
| 33 | |
| 34 | // shortTime prints only the time of day. Someone reading a terminal doesn't |
| 35 | // need the date and time zone on every line; a log collector does. |
| 36 | func shortTime(groups []string, a slog.Attr) slog.Attr { |
| 37 | if a.Key == slog.TimeKey && len(groups) == 0 { |
| 38 | a.Value = slog.StringValue(a.Value.Time().Format("15:04:05.000")) |
| 39 | } |
| 40 | return a |
| 41 | } |
| 42 | |
| 43 | // ParseLevel parses debug, info, warn or error, in upper or lower case. |
| 44 | func ParseLevel(s string) (slog.Level, error) { |
| 45 | var l slog.Level |
| 46 | err := l.UnmarshalText([]byte(s)) |
| 47 | return l, err |
| 48 | } |