1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
package logflags
import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"time"
)
// Logger represents a generic interface for logging inside of
// Delve codebase.
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Debug(...interface{})
Info(...interface{})
Warn(...interface{})
Error(...interface{})
}
// LoggerFactory is used to create new Logger instances.
// SetLoggerFactory can be used to configure it.
//
// The given parameters fields and out can be both be nil.
type LoggerFactory func(flag bool, fields Fields, out io.Writer) Logger
var loggerFactory LoggerFactory
// SetLoggerFactory will ensure that every Logger created by this package, will be now created
// by the given LoggerFactory. Default behavior will be a slog based Logger instance using DefaultFormatter.
func SetLoggerFactory(lf LoggerFactory) {
loggerFactory = lf
}
// Fields type wraps many fields for Logger
type Fields map[string]interface{}
type slogLogger struct {
s *slog.Logger
}
func sloglog(logger *slog.Logger, level slog.Level, thunk func() string) {
// see the "Wrapping" example in the documentation of log/slog
if !logger.Enabled(context.Background(), slog.LevelDebug) {
return
}
var pcs [1]uintptr
runtime.Callers(3, pcs[:]) // skip [ runtime.Callers, sloglog, the caller of this function ]
r := slog.NewRecord(time.Now(), level, thunk(), pcs[0])
_ = logger.Handler().Handle(context.Background(), r)
}
func (s slogLogger) Debugf(format string, args ...interface{}) {
sloglog(s.s, slog.LevelDebug, func() string {
return fmt.Sprintf(format, args...)
})
}
func (s slogLogger) Infof(format string, args ...interface{}) {
sloglog(s.s, slog.LevelInfo, func() string {
return fmt.Sprintf(format, args...)
})
}
func (s slogLogger) Warnf(format string, args ...interface{}) {
sloglog(s.s, slog.LevelWarn, func() string {
return fmt.Sprintf(format, args...)
})
}
func (s slogLogger) Errorf(format string, args ...interface{}) {
sloglog(s.s, slog.LevelError, func() string {
return fmt.Sprintf(format, args...)
})
}
func (s slogLogger) Debug(args ...interface{}) {
sloglog(s.s, slog.LevelDebug, func() string {
return fmt.Sprint(args...)
})
}
func (s slogLogger) Info(args ...interface{}) {
sloglog(s.s, slog.LevelInfo, func() string {
return fmt.Sprint(args...)
})
}
func (s slogLogger) Warn(args ...interface{}) {
sloglog(s.s, slog.LevelWarn, func() string {
return fmt.Sprint(args...)
})
}
func (s slogLogger) Error(args ...interface{}) {
sloglog(s.s, slog.LevelError, func() string {
return fmt.Sprint(args...)
})
}
|