package simplelog import ( "context" "fmt" "log/slog" "runtime" "time" "github.com/fatih/color" ) type ConsoleHandler struct { attrs handlerAttrs } func NewConsoleHandler() *ConsoleHandler { return &ConsoleHandler{} } func (c *ConsoleHandler) Handle( ctx context.Context, record slog.Record, ) error { timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z07:00") var colorFunc func(format string, a ...interface{}) string switch record.Level { case slog.LevelInfo: colorFunc = color.New(color.FgBlue).SprintfFunc() case slog.LevelWarn: colorFunc = color.New(color.FgYellow).SprintfFunc() case slog.LevelError: colorFunc = color.New(color.FgRed).SprintfFunc() default: colorFunc = color.New(color.FgWhite).SprintfFunc() } // Get the caller information _, file, line, ok := runtime.Caller(4) if !ok { file = "???" line = 0 } fmt.Println( colorFunc( "%s [%s] %s:%d: %s%s", timestamp, record.Level, file, line, record.Message, attrsToText(c.attrs.forRecord(record)), ), ) return nil } func (c *ConsoleHandler) Enabled( ctx context.Context, level slog.Level, ) bool { return true } func (c *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return c } return &ConsoleHandler{attrs: c.attrs.withAttrs(attrs)} } func (c *ConsoleHandler) WithGroup(name string) slog.Handler { if name == "" { return c } return &ConsoleHandler{attrs: c.attrs.withGroup(name)} }