logging/module.go

82 lines
1.6 KiB
Go
Raw Permalink Normal View History

2025-03-27 16:14:28 +01:00
package logging
import (
"errors"
"io"
"log/slog"
"netgarden.dev/maf/maf"
"os"
"strings"
)
func NewModule() *Module {
return &Module{}
}
type Module struct {
manager *maf.Manager
config *Config
}
func (m *Module) GetID() string {
return "logging"
}
func (m *Module) GetName() string {
return "logging"
}
func (m *Module) SetManager(manager *maf.Manager) {
m.manager = manager
}
func (m *Module) CreateConfig() interface{} {
return NewConfig()
}
func (m *Module) SetConfig(config interface{}) {
m.config = config.(*Config)
}
func (m *Module) setupLogging() error {
var w io.Writer
var level slog.Level
var handler slog.Handler
if strings.EqualFold("stdout", m.config.Destination) {
w = os.Stdout
} else {
return errors.New("Unknown logging destination: " + m.config.Destination)
}
if strings.EqualFold("debug", m.config.Level) {
level = slog.LevelDebug
} else if strings.EqualFold("info", m.config.Level) {
level = slog.LevelInfo
} else if strings.EqualFold("warn", m.config.Level) {
level = slog.LevelWarn
} else if strings.EqualFold("error", m.config.Level) {
level = slog.LevelError
} else {
return errors.New("Unknown logging level: " + m.config.Level)
}
options := &slog.HandlerOptions{
Level: level,
}
if strings.EqualFold("text", m.config.Format) {
handler = slog.NewTextHandler(w, options)
} else if strings.EqualFold("json", m.config.Format) {
handler = slog.NewJSONHandler(w, options)
} else {
return errors.New("Unknown logging format: " + m.config.Format)
}
logger := slog.New(handler)
slog.SetDefault(logger)
return nil
}