Skip to content

Commit

Permalink
fix named
Browse files Browse the repository at this point in the history
Signed-off-by: Pavel Okhlopkov <[email protected]>
  • Loading branch information
Pavel Okhlopkov committed Oct 29, 2024
1 parent e37695d commit 8ef9a52
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
26 changes: 18 additions & 8 deletions pkg/unilogger/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"runtime"
Expand Down Expand Up @@ -36,6 +37,8 @@ type SlogHandler struct {
b *bytes.Buffer
m *sync.Mutex

name string

timeFn func(t time.Time) time.Time
}

Expand All @@ -59,6 +62,7 @@ func (h *SlogHandler) Handle(ctx context.Context, r slog.Record) error {

isCustom := logContext.GetCustomKeyContext(ctx)
if isCustom {
// r.PC, _, _, _ = runtime.Caller(4)
var pc uintptr
var pcs [1]uintptr
// skip [runtime.Callers, this function, this function's caller]
Expand All @@ -84,15 +88,9 @@ func (h *SlogHandler) Handle(ctx context.Context, r slog.Record) error {
Message: r.Message,
}

// if logger was named
loggerName, ok := attrs["logger"]
if ok {
logOutput.Name = loggerName.(string)

delete(attrs, "logger")
}
logOutput.Name = h.name

// if logger was named
// if logger was traced - remove source
if tracePtr != nil {
logOutput.Stacktrace = *tracePtr

Expand Down Expand Up @@ -143,6 +141,18 @@ func (h *SlogHandler) WithGroup(name string) slog.Handler {
return &h2
}

func (h *SlogHandler) Named(name string) slog.Handler {
currName := name
if h.name != "" {
currName = fmt.Sprintf("%s.%s", h.name, name)
}

h2 := *h
h2.name = currName

return &h2
}

func NewHandler(out io.Writer, opts *slog.HandlerOptions, timeFn func(t time.Time) time.Time) *SlogHandler {
b := new(bytes.Buffer)

Expand Down
9 changes: 2 additions & 7 deletions pkg/unilogger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,11 @@ func (l *Logger) SetOutput(w io.Writer) {
}

func (l *Logger) Named(name string) *Logger {
currName := name
if l.name != "" {
currName = fmt.Sprintf("%s.%s", l.name, name)
}

return &Logger{
logger: l.logger.With(slog.String("logger", currName)),
logger: slog.New(l.Handler().(*SlogHandler).Named(name)),
addSourceVar: l.addSourceVar,
level: l.level,
name: currName,
name: l.name,
}
}

Expand Down

0 comments on commit 8ef9a52

Please sign in to comment.