This commit is contained in:
Felipe M 2025-05-13 11:52:37 +02:00
commit 1a4986f294
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8
18 changed files with 3181 additions and 0 deletions

91
pkg/logger/logger.go Normal file
View file

@ -0,0 +1,91 @@
package logger
import (
"io"
"log/slog"
"os"
"time"
"github.com/lmittmann/tint"
)
var (
// Default logger is a tinted logger that writes to stdout
defaultLogger *slog.Logger
// Debug flag controls verbose logging
debugMode bool
)
// Init initializes the global logger with the specified debug level
func Init(debug bool) {
debugMode = debug
// Set the minimum log level based on debug mode
level := slog.LevelInfo
if debug {
level = slog.LevelDebug
}
// Create a tinted logger with time, level, and source
defaultLogger = slog.New(
tint.NewHandler(os.Stdout, &tint.Options{
Level: level,
TimeFormat: time.RFC3339,
AddSource: debug,
}),
)
// Set the default slog logger
slog.SetDefault(defaultLogger)
}
// InitWithWriter initializes the logger with a custom writer (useful for testing)
func InitWithWriter(w io.Writer, debug bool) {
debugMode = debug
level := slog.LevelInfo
if debug {
level = slog.LevelDebug
}
defaultLogger = slog.New(
tint.NewHandler(w, &tint.Options{
Level: level,
TimeFormat: time.RFC3339,
AddSource: debug,
}),
)
slog.SetDefault(defaultLogger)
}
// IsDebug returns true if debug mode is enabled
func IsDebug() bool {
return debugMode
}
// Debug logs a message at debug level
func Debug(msg string, args ...any) {
slog.Debug(msg, args...)
}
// Info logs a message at info level
func Info(msg string, args ...any) {
slog.Info(msg, args...)
}
// Warn logs a message at warn level
func Warn(msg string, args ...any) {
slog.Warn(msg, args...)
}
// Error logs a message at error level
func Error(msg string, args ...any) {
slog.Error(msg, args...)
}
// With returns a new logger with the given attributes
func With(args ...any) *slog.Logger {
return slog.With(args...)
}