update slog/logger #351

Merged
vtolstov merged 11 commits from devstigneev/micro:fix_attrs_logger into v3 2024-10-12 12:37:44 +03:00
3 changed files with 15 additions and 3 deletions
Showing only changes of commit ced277ff57 - Show all commits

View File

@ -14,6 +14,8 @@ var (
DefaultLogger Logger = NewLogger()
// DefaultLevel used by logger
DefaultLevel = InfoLevel
// defaultCallerSkipCount used by logger
defaultCallerSkipCount = 3
)
// Logger is a generic logging interface

View File

@ -23,6 +23,8 @@ type Options struct {
Name string
// Fields holds additional metadata
Fields []interface{}
// callerSkipCount number of frmaes to skip
CallerSkipCount int
// ContextAttrFuncs contains funcs that executed before log func on context
ContextAttrFuncs []ContextAttrFunc
// TimeKey is the key used for the time of the log call
@ -52,6 +54,7 @@ type Options struct {
// NewOptions creates new options struct
func NewOptions(opts ...Option) Options {
options := Options{
CallerSkipCount: defaultCallerSkipCount,
Level: DefaultLevel,
Fields: make([]interface{}, 0, 6),
Out: os.Stderr,
@ -184,3 +187,12 @@ func WithMicroKeys() Option {
o.ErrorKey = "error"
}
}
// WithAddCallerSkipCount add skip count for copy logger
func WithAddCallerSkipCount(n int) Option {
return func(o *Options) {
if n > 0 {
o.CallerSkipCount += n
}
}
}

View File

@ -16,8 +16,6 @@ import (
const (
badKey = "!BADKEY"
// DefaultCallerSkipCount used by logger
defaultCallerSkipCount = 3
)
const emptyMSg = "!EMPTYMSG"
@ -227,7 +225,7 @@ func (s *slogLogger) printLog(ctx context.Context, lvl logger.Level, msg string,
}
var pcs [1]uintptr
runtime.Callers(defaultCallerSkipCount, pcs[:]) // skip [Callers, printLog, LogLvlMethod]
runtime.Callers(s.opts.CallerSkipCount, pcs[:]) // skip [Callers, printLog, LogLvlMethod]
r := slog.NewRecord(s.opts.TimeFunc(), loggerToSlogLevel(lvl), msg, pcs[0])
r.Add(attrs...)
_ = s.handler.Handle(ctx, r)