You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gomud/logger/wrappedslogger.go

103 lines
2.1 KiB
Go

package logger
1 year ago
import (
"io"
1 year ago
"log/slog"
"github.com/ThreeDotsLabs/watermill"
)
const (
LevelTrace = slog.Level(-5)
)
1 year ago
func LogFieldsToSlogAttrs(in watermill.LogFields) []slog.Attr {
attrs := make([]slog.Attr, 0)
for k, v := range in {
attrs = append(attrs, slog.Attr{
Key: k,
Value: slog.AnyValue(v),
})
}
return attrs
}
type WrappedSlogger struct {
loggers []*slog.Logger
1 year ago
}
type LogConfig struct {
Format string
Writer io.Writer
Level int
}
func NewWrappedSlogger(configs ...LogConfig) *WrappedSlogger {
loggers := make([]*slog.Logger, 0)
for _, config := range configs {
opts := &slog.HandlerOptions{
Level: slog.Level(config.Level),
}
var handler slog.Handler
switch config.Format {
case "json":
handler = slog.NewJSONHandler(config.Writer, opts)
case "text":
handler = slog.NewTextHandler(config.Writer, opts)
}
loggers = append(loggers, slog.New(handler))
}
1 year ago
return &WrappedSlogger{
loggers: loggers,
1 year ago
}
}
func (wl *WrappedSlogger) Error(msg string, err error, fields watermill.LogFields) {
attrs := LogFieldsToSlogAttrs(fields)
for _, l := range wl.loggers {
l.LogAttrs(nil, slog.LevelError, msg, attrs...)
}
1 year ago
}
func (wl *WrappedSlogger) Info(msg string, fields watermill.LogFields) {
attrs := LogFieldsToSlogAttrs(fields)
for _, l := range wl.loggers {
l.LogAttrs(nil, slog.LevelInfo, msg, attrs...)
}
1 year ago
}
func (wl *WrappedSlogger) Debug(msg string, fields watermill.LogFields) {
attrs := LogFieldsToSlogAttrs(fields)
for _, l := range wl.loggers {
l.LogAttrs(nil, slog.LevelDebug, msg, attrs...)
}
1 year ago
}
func (wl *WrappedSlogger) Trace(msg string, fields watermill.LogFields) {
attrs := LogFieldsToSlogAttrs(fields)
for _, l := range wl.loggers {
l.LogAttrs(nil, LevelTrace, msg, attrs...)
}
1 year ago
}
func (wl *WrappedSlogger) With(fields watermill.LogFields) watermill.LoggerAdapter {
attrs := LogFieldsToSlogAttrs(fields)
loggerArgs := make([]any, len(attrs))
for idx, attr := range attrs {
loggerArgs[idx] = attr
}
newLoggers := make([]*slog.Logger, 0)
for _, l := range wl.loggers {
newLoggers = append(newLoggers, l.With(loggerArgs...))
}
return &WrappedSlogger{loggers: newLoggers}
1 year ago
}