Skip to content

Commit

Permalink
added option to change level labels
Browse files Browse the repository at this point in the history
Small change gives the caller the ability to use custom labels.
For example, if they want to see "INFO" instead of "INF"
  • Loading branch information
BacchusJackson committed Aug 26, 2023
1 parent 8c0ec83 commit c71e378
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
22 changes: 18 additions & 4 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ type Options struct {

// Disable color (Default: false)
NoColor bool

// Labels used for each label (Default: DBG,INF,WRN,ERR)
Labels [4]string
}

// NewHandler creates a [slog.Handler] that writes tinted logs to Writer w,
Expand All @@ -127,6 +130,15 @@ func NewHandler(w io.Writer, opts *Options) slog.Handler {
h.timeFormat = opts.TimeFormat
}
h.noColor = opts.NoColor

h.Labels = [4]string{"DBG", "INF", "WRN", "ERR"}

for i := range opts.Labels {
if opts.Labels[i] != "" {
h.Labels[i] = opts.Labels[i]
}
}

return h
}

Expand All @@ -144,6 +156,8 @@ type handler struct {
replaceAttr func([]string, slog.Attr) slog.Attr
timeFormat string
noColor bool

Labels [4]string
}

func (h *handler) clone() *handler {
Expand Down Expand Up @@ -303,21 +317,21 @@ func (h *handler) appendLevel(buf *buffer, level slog.Level) {

switch {
case level < slog.LevelInfo:
buf.WriteString("DBG")
buf.WriteString(h.Labels[0])
delta(buf, level-slog.LevelDebug)
case level < slog.LevelWarn:
buf.WriteStringIf(!h.noColor, ansiBrightGreen)
buf.WriteString("INF")
buf.WriteString(h.Labels[1])
delta(buf, level-slog.LevelInfo)
buf.WriteStringIf(!h.noColor, ansiReset)
case level < slog.LevelError:
buf.WriteStringIf(!h.noColor, ansiBrightYellow)
buf.WriteString("WRN")
buf.WriteString(h.Labels[2])
delta(buf, level-slog.LevelWarn)
buf.WriteStringIf(!h.noColor, ansiReset)
default:
buf.WriteStringIf(!h.noColor, ansiBrightRed)
buf.WriteString("ERR")
buf.WriteString(h.Labels[3])
delta(buf, level-slog.LevelError)
buf.WriteStringIf(!h.noColor, ansiReset)
}
Expand Down
10 changes: 10 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@ func TestHandler(t *testing.T) {
},
Want: `Nov 10 23:00:00.000 INF tint/handler_test.go:99 test key=val`,
},
{
Opts: &tint.Options{
AddSource: true,
Labels: [4]string{"DEBUG", "INFO", "WARN", "ERROR"},
},
F: func(l *slog.Logger) {
l.Info("test", "key", "val")
},
Want: `Nov 10 23:00:00.000 INFO tint/handler_test.go:99 test key=val`,
},
{
Opts: &tint.Options{
TimeFormat: time.Kitchen,
Expand Down

0 comments on commit c71e378

Please sign in to comment.