58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
|
package logx
|
||
|
|
||
|
import (
|
||
|
"io"
|
||
|
"log/slog"
|
||
|
"os"
|
||
|
|
||
|
"github.com/fatih/color"
|
||
|
)
|
||
|
|
||
|
type ConsoleHandler struct {
|
||
|
slog.Handler
|
||
|
w io.Writer
|
||
|
}
|
||
|
|
||
|
func NewConsoleHandler(level slog.Level) *ConsoleHandler {
|
||
|
return &ConsoleHandler{
|
||
|
Handler: slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
|
||
|
Level: level,
|
||
|
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||
|
if a.Key == slog.LevelKey {
|
||
|
level := a.Value.Any().(slog.Level)
|
||
|
switch level {
|
||
|
case slog.LevelDebug:
|
||
|
a.Value = slog.StringValue(color.BlueString(level.String()))
|
||
|
case slog.LevelInfo:
|
||
|
a.Value = slog.StringValue(color.GreenString(level.String()))
|
||
|
case slog.LevelWarn:
|
||
|
a.Value = slog.StringValue(color.YellowString(level.String()))
|
||
|
case slog.LevelError:
|
||
|
a.Value = slog.StringValue(color.RedString(level.String()))
|
||
|
}
|
||
|
}
|
||
|
return a
|
||
|
},
|
||
|
}),
|
||
|
w: os.Stdout,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (h *ConsoleHandler) Close() error {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||
|
return &ConsoleHandler{
|
||
|
Handler: h.Handler.WithAttrs(attrs),
|
||
|
w: h.w,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func WithConsoleHandler(level slog.Level) Option {
|
||
|
return func(l *Logger) {
|
||
|
h := NewConsoleHandler(level)
|
||
|
l.handlers = append(l.handlers, h)
|
||
|
}
|
||
|
}
|