goshort/internal/util/logging/logging.go
Gustavo Maronato 371de006ad
All checks were successful
Build / build (push) Successful in 25m7s
add verbose
2023-09-06 18:43:56 -03:00

51 lines
948 B
Go

package logging
import (
"context"
"log/slog"
"os"
"git.maronato.dev/maronato/goshort/internal/config"
)
type logCtxKey struct{}
func NewLogger(cfg *config.Config) *slog.Logger {
level := slog.LevelInfo
addSource := false
if cfg.Verbose >= config.VerboseLevelDebug {
level = slog.LevelDebug
addSource = true
}
if cfg.Verbose <= config.VerboseLevelQuiet {
level = slog.LevelError
}
if cfg.Prod {
return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
AddSource: addSource,
}))
}
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
AddSource: addSource,
}))
}
func FromCtx(ctx context.Context) *slog.Logger {
l, ok := ctx.Value(logCtxKey{}).(*slog.Logger)
if !ok {
return slog.New(NewNoOpHandler())
}
return l
}
func WithLogger(ctx context.Context, l *slog.Logger) context.Context {
return context.WithValue(ctx, logCtxKey{}, l)
}