logger.go raw

   1  package viper
   2  
   3  import (
   4  	"context"
   5  
   6  	slog "github.com/sagikazarmark/slog-shim"
   7  )
   8  
   9  // Logger is a unified interface for various logging use cases and practices, including:
  10  //   - leveled logging
  11  //   - structured logging
  12  //
  13  // Deprecated: use `log/slog` instead.
  14  type Logger interface {
  15  	// Trace logs a Trace event.
  16  	//
  17  	// Even more fine-grained information than Debug events.
  18  	// Loggers not supporting this level should fall back to Debug.
  19  	Trace(msg string, keyvals ...any)
  20  
  21  	// Debug logs a Debug event.
  22  	//
  23  	// A verbose series of information events.
  24  	// They are useful when debugging the system.
  25  	Debug(msg string, keyvals ...any)
  26  
  27  	// Info logs an Info event.
  28  	//
  29  	// General information about what's happening inside the system.
  30  	Info(msg string, keyvals ...any)
  31  
  32  	// Warn logs a Warn(ing) event.
  33  	//
  34  	// Non-critical events that should be looked at.
  35  	Warn(msg string, keyvals ...any)
  36  
  37  	// Error logs an Error event.
  38  	//
  39  	// Critical events that require immediate attention.
  40  	// Loggers commonly provide Fatal and Panic levels above Error level,
  41  	// but exiting and panicking is out of scope for a logging library.
  42  	Error(msg string, keyvals ...any)
  43  }
  44  
  45  // WithLogger sets a custom logger.
  46  func WithLogger(l *slog.Logger) Option {
  47  	return optionFunc(func(v *Viper) {
  48  		v.logger = l
  49  	})
  50  }
  51  
  52  type discardHandler struct{}
  53  
  54  func (n *discardHandler) Enabled(_ context.Context, _ slog.Level) bool {
  55  	return false
  56  }
  57  
  58  func (n *discardHandler) Handle(_ context.Context, _ slog.Record) error {
  59  	return nil
  60  }
  61  
  62  func (n *discardHandler) WithAttrs(_ []slog.Attr) slog.Handler {
  63  	return n
  64  }
  65  
  66  func (n *discardHandler) WithGroup(_ string) slog.Handler {
  67  	return n
  68  }
  69