Skip to content

Commit

Permalink
feat: enable users to add caller
Browse files Browse the repository at this point in the history
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
  • Loading branch information
knight42 committed Mar 16, 2023
1 parent 24573ce commit 1ae5945
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
2 changes: 1 addition & 1 deletion exp/zapslog/example_test.go
Expand Up @@ -45,7 +45,7 @@ func Example_slog() {
ctx := context.Background()

sl.Info("user", "name", "Al", "secret", Password("secret"))
sl.Error("oops", net.ErrClosed, "status", 500)
sl.Error("oops", "err", net.ErrClosed, "status", 500)
sl.LogAttrs(ctx, slog.LevelError, "oops",
slog.Any("err", net.ErrClosed), slog.Int("status", 500))
sl.Info("message",
Expand Down
29 changes: 24 additions & 5 deletions exp/zapslog/slog.go
Expand Up @@ -22,6 +22,7 @@ package zapslog

import (
"context"
"runtime"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand All @@ -30,8 +31,9 @@ import (

// Handler implements the slog.Handler by writing to a zap Core.
type Handler struct {
core zapcore.Core
name string // logger name
core zapcore.Core
name string // logger name
addSource bool
}

// HandlerOptions are options for a Zap-based [slog.Handler].
Expand All @@ -40,14 +42,21 @@ type HandlerOptions struct {
//
// Defaults to empty.
LoggerName string

// AddSource configures the handler to annotate each message with the filename,
// line number, and function name.
// AddSource is false by default to skip the cost of computing
// this information.
AddSource bool
}

// New builds a [Handler] that writes to the supplied [zapcore.Core].
// This handler may be supplied to [slog.New] to create a new [slog.Logger].
func (opts HandlerOptions) New(core zapcore.Core) *Handler {
return &Handler{
core: core,
name: opts.LoggerName,
core: core,
name: opts.LoggerName,
addSource: opts.AddSource,
}
}

Expand Down Expand Up @@ -128,14 +137,24 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
Message: record.Message,
LoggerName: h.name,
// FIXME: do we need to set the following fields?
// Caller:
// Stack:
}
ce := h.core.Check(ent, nil)
if ce == nil {
return nil
}

if h.addSource {
frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next()
ce.Entry.Caller = zapcore.EntryCaller{
Defined: true,
PC: frame.PC,
File: frame.File,
Line: frame.Line,
Function: frame.Function,
}
}

fields := make([]zapcore.Field, 0, record.NumAttrs())
record.Attrs(func(attr slog.Attr) {
fields = append(fields, convertAttrToField(attr))
Expand Down

0 comments on commit 1ae5945

Please sign in to comment.