@@ -22,6 +22,7 @@ package zapslog
2222
2323import (
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.
3233type 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].
4755func (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