Skip to content

Commit 1ae5945

Browse files
committed
feat: enable users to add caller
Signed-off-by: Jian Zeng <[email protected]>
1 parent 24573ce commit 1ae5945

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

exp/zapslog/example_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func Example_slog() {
4545
ctx := context.Background()
4646

4747
sl.Info("user", "name", "Al", "secret", Password("secret"))
48-
sl.Error("oops", net.ErrClosed, "status", 500)
48+
sl.Error("oops", "err", net.ErrClosed, "status", 500)
4949
sl.LogAttrs(ctx, slog.LevelError, "oops",
5050
slog.Any("err", net.ErrClosed), slog.Int("status", 500))
5151
sl.Info("message",

exp/zapslog/slog.go

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ package zapslog
2222

2323
import (
2424
"context"
25+
"runtime"
2526

2627
"go.uber.org/zap"
2728
"go.uber.org/zap/zapcore"
@@ -30,8 +31,9 @@ import (
3031

3132
// Handler implements the slog.Handler by writing to a zap Core.
3233
type Handler struct {
33-
core zapcore.Core
34-
name string // logger name
34+
core zapcore.Core
35+
name string // logger name
36+
addSource bool
3537
}
3638

3739
// HandlerOptions are options for a Zap-based [slog.Handler].
@@ -40,14 +42,21 @@ type HandlerOptions struct {
4042
//
4143
// Defaults to empty.
4244
LoggerName string
45+
46+
// AddSource configures the handler to annotate each message with the filename,
47+
// line number, and function name.
48+
// AddSource is false by default to skip the cost of computing
49+
// this information.
50+
AddSource bool
4351
}
4452

4553
// New builds a [Handler] that writes to the supplied [zapcore.Core].
4654
// This handler may be supplied to [slog.New] to create a new [slog.Logger].
4755
func (opts HandlerOptions) New(core zapcore.Core) *Handler {
4856
return &Handler{
49-
core: core,
50-
name: opts.LoggerName,
57+
core: core,
58+
name: opts.LoggerName,
59+
addSource: opts.AddSource,
5160
}
5261
}
5362

@@ -128,14 +137,24 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
128137
Message: record.Message,
129138
LoggerName: h.name,
130139
// FIXME: do we need to set the following fields?
131-
// Caller:
132140
// Stack:
133141
}
134142
ce := h.core.Check(ent, nil)
135143
if ce == nil {
136144
return nil
137145
}
138146

147+
if h.addSource {
148+
frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next()
149+
ce.Entry.Caller = zapcore.EntryCaller{
150+
Defined: true,
151+
PC: frame.PC,
152+
File: frame.File,
153+
Line: frame.Line,
154+
Function: frame.Function,
155+
}
156+
}
157+
139158
fields := make([]zapcore.Field, 0, record.NumAttrs())
140159
record.Attrs(func(attr slog.Attr) {
141160
fields = append(fields, convertAttrToField(attr))

0 commit comments

Comments
 (0)