internal/testlog, log: add Inner method to log.Logger to expose wrapped slog.Logger. fix log.SetDefault to also set slog default logger.

This commit is contained in:
Jared Wasinger 2023-11-21 23:03:48 +08:00
parent ec2e836aa3
commit 98166316b9
3 changed files with 20 additions and 13 deletions

View file

@ -98,8 +98,8 @@ func LoggerWithHandler(t *testing.T, handler slog.Handler) log.Logger {
}
}
func (l *logger) Handler() slog.Handler {
return l.l.Handler()
func (l *logger) Inner() *slog.Logger {
return l.l.Inner()
}
func (l *logger) Trace(msg string, ctx ...interface{}) {

View file

@ -105,9 +105,6 @@ func LevelString(l slog.Level) string {
// A Logger writes key/value pairs to a Handler
type Logger interface {
// Handler returns the handler associated with this logger
Handler() slog.Handler
// TODO: add WithGroup()?
// With returns a new Logger that has this logger's attributes plus the given attributes
@ -136,6 +133,9 @@ type Logger interface {
// Crit logs a message at the crit level with context key/value pairs, and exits
Crit(msg string, ctx ...interface{})
// Inner returns the underlying slog logger that is wrapped
Inner() *slog.Logger
}
type logger struct {
@ -149,8 +149,9 @@ func NewLogger(h slog.Handler) Logger {
}
}
func (l *logger) Handler() slog.Handler {
return l.inner.Handler()
// Inner returns the underlying slog logger that
func (l *logger) Inner() *slog.Logger {
return l.inner
}
// write logs a message at the specified level:

View file

@ -2,22 +2,26 @@ package log
import (
"os"
"sync/atomic"
"sync"
"golang.org/x/exp/slog"
)
var (
root = new(atomic.Value)
rootMu sync.Mutex
root logger
)
func init() {
defaultLogger := &logger{slog.New(DiscardHandler())}
root.Store(defaultLogger)
SetDefault(defaultLogger)
}
func SetDefault(l Logger) {
root.Store(l)
rootMu.Lock()
defer rootMu.Unlock()
root := l
slog.SetDefault(root.Inner())
}
// Root returns the root logger
@ -26,8 +30,10 @@ func Root() Logger {
}
func rootLogger() *logger {
res, _ := root.Load().(*logger)
return res
rootMu.Lock()
defer rootMu.Unlock()
res := root
return &res
}
// The following functions bypass the exported logger methods (logger.Debug,