133 lines
2.9 KiB
Go

package config
import (
"context"
"log/slog"
"reflect"
"strconv"
)
const (
LevelTrace = slog.Level(-8)
LevelFatal = slog.Level(12)
)
type Log struct {
Ctx context.Context
Log *slog.Logger
SLogLevel *slog.LevelVar
}
var LevelNames = map[slog.Leveler]string{
LevelTrace: "TRACE",
LevelFatal: "FATAL",
}
func setLogLevel(cfg *Config) {
switch {
// fatal
case cfg.LogLevel <= 20:
cfg.Log.SLogLevel.Set(LevelFatal)
cfg.Log.Info("Log level updated", slog.Any("level", LevelFatal))
// error
case cfg.LogLevel > 20 && cfg.LogLevel <= 40:
cfg.Log.SLogLevel.Set(slog.LevelError)
cfg.Log.Info("Log level updated", slog.Any("level", slog.LevelError))
// warning
case cfg.LogLevel > 40 && cfg.LogLevel <= 60:
cfg.Log.SLogLevel.Set(slog.LevelWarn)
cfg.Log.Info("Log level updated", slog.Any("level", slog.LevelWarn))
// info
case cfg.LogLevel > 60 && cfg.LogLevel <= 80:
cfg.Log.SLogLevel.Set(slog.LevelInfo)
cfg.Log.Info("Log level updated", slog.Any("level", slog.LevelInfo))
// debug
case cfg.LogLevel > 80 && cfg.LogLevel <= 100:
cfg.Log.SLogLevel.Set(slog.LevelDebug)
cfg.Log.Info("Log level updated", slog.Any("level", slog.LevelDebug))
// trace
case cfg.LogLevel > 100:
cfg.Log.SLogLevel.Set(LevelTrace)
cfg.Log.Info("Log level updated", slog.Any("level", LevelTrace))
}
// set default logger
slog.SetDefault(cfg.Log.Log)
}
func printRunningConfig(cfg *Config, cfgInfo []structInfo) {
var logRunningConfiguration string = "Running Configuration"
for _, info := range cfgInfo {
if info.Secret {
cfg.Log.Debug(logRunningConfiguration, info.Name, "REDACTED")
} else {
switch info.Type.String() {
case "string":
p := reflect.ValueOf(cfg).Elem().FieldByName(info.Name).Addr().Interface().(*string)
cfg.Log.Debug(logRunningConfiguration, info.Alt, *p)
case "bool":
p := reflect.ValueOf(cfg).Elem().FieldByName(info.Name).Addr().Interface().(*bool)
cfg.Log.Debug(logRunningConfiguration, info.Alt, strconv.FormatBool(*p))
case "int":
p := reflect.ValueOf(cfg).Elem().FieldByName(info.Name).Addr().Interface().(*int)
cfg.Log.Debug(logRunningConfiguration, info.Alt, strconv.FormatInt(int64(*p), 10))
}
}
}
}
func (log *Log) Fatal(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
LevelFatal,
msg,
attrs...,
)
}
func (log Log) Error(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
slog.LevelError,
msg,
attrs...,
)
}
func (log Log) Warn(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
slog.LevelWarn,
msg,
attrs...,
)
}
func (log Log) Info(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
slog.LevelInfo,
msg,
attrs...,
)
}
func (log Log) Debug(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
slog.LevelDebug,
msg,
attrs...,
)
}
func (log Log) Trace(msg string, attrs ...interface{}) {
log.Log.Log(
log.Ctx,
LevelTrace,
msg,
attrs...,
)
}