98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"log/slog"
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
// Мьютекс для предотвращения наложения строк из горутин
|
||
|
var mu = new(sync.Mutex)
|
||
|
|
||
|
type Handler struct {
|
||
|
w io.Writer
|
||
|
level slog.Level
|
||
|
}
|
||
|
|
||
|
func (h *Handler) Enabled(c context.Context, l slog.Level) bool {
|
||
|
return l >= h.level
|
||
|
}
|
||
|
|
||
|
func (h *Handler) Handle(c context.Context, r slog.Record) error {
|
||
|
mu.Lock()
|
||
|
defer mu.Unlock()
|
||
|
|
||
|
switch r.Level {
|
||
|
case slog.LevelError:
|
||
|
fmt.Fprintf(h.w, "• ОШИБКА: %v\n", r.Message)
|
||
|
|
||
|
r.Attrs(func(a slog.Attr) bool {
|
||
|
s := fmt.Sprintf(" %v=%v\n", a.Key, a.Value)
|
||
|
fmt.Fprint(h.w, s)
|
||
|
return true
|
||
|
})
|
||
|
default:
|
||
|
fmt.Fprintf(h.w, "• %v ", r.Message)
|
||
|
|
||
|
r.Attrs(func(a slog.Attr) bool {
|
||
|
s := fmt.Sprintf("%v=%v ", a.Key, a.Value)
|
||
|
fmt.Fprint(h.w, s)
|
||
|
return true
|
||
|
})
|
||
|
fmt.Fprint(h.w, "\n")
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
/*func (h *Handler) HandleColor(c context.Context, r slog.Record) error {
|
||
|
var yellow = color.New(color.FgYellow).SprintFunc()
|
||
|
|
||
|
switch r.Level {
|
||
|
case slog.LevelError:
|
||
|
redHi := color.New(color.FgHiRed).SprintFunc()
|
||
|
fmt.Fprintf(h.w, redHi("• %v\n"), r.Message)
|
||
|
|
||
|
red := color.New(color.FgRed).SprintFunc()
|
||
|
r.Attrs(func(a slog.Attr) bool {
|
||
|
s := fmt.Sprintf(" %v=%v\n", red(a.Key), a.Value)
|
||
|
fmt.Fprint(h.w, s)
|
||
|
return true
|
||
|
})
|
||
|
case slog.LevelWarn:
|
||
|
fmt.Fprintf(h.w, yellow("• %v\n"), r.Message)
|
||
|
|
||
|
red := color.New(color.FgRed).SprintFunc()
|
||
|
r.Attrs(func(a slog.Attr) bool {
|
||
|
s := fmt.Sprintf(" %v=%v\n", red(a.Key), yellow(a.Value))
|
||
|
fmt.Fprint(h.w, s)
|
||
|
return true
|
||
|
})
|
||
|
default:
|
||
|
fmt.Fprintf(h.w, "• %v ", r.Message)
|
||
|
|
||
|
r.Attrs(func(a slog.Attr) bool {
|
||
|
s := fmt.Sprintf("%v=%v ", yellow(a.Key), a.Value)
|
||
|
fmt.Fprint(h.w, s)
|
||
|
return true
|
||
|
})
|
||
|
fmt.Fprint(h.w, "\n")
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}*/
|
||
|
|
||
|
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||
|
return h
|
||
|
}
|
||
|
|
||
|
func (h *Handler) WithGroup(name string) slog.Handler {
|
||
|
return h
|
||
|
}
|
||
|
|
||
|
func (h *Handler) SetLevel(level slog.Level) {
|
||
|
h.level = level
|
||
|
}
|