-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaller-handler.go
42 lines (35 loc) · 905 Bytes
/
caller-handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package logging
import (
"context"
"log/slog"
"runtime"
)
type callerHandler struct {
addSource bool
next slog.Handler
}
func (c *callerHandler) Enabled(ctx context.Context, level slog.Level) bool {
return c.next.Enabled(ctx, level)
}
func (c *callerHandler) Handle(ctx context.Context, r slog.Record) error {
if c.addSource {
// get caller who called the function, not the function itself
var pcs [1]uintptr
runtime.Callers(3, pcs[:]) // skip [Callers, <Log>f, callerHandler.Handle]
// assign program counter
r.PC = pcs[0]
}
return c.next.Handle(ctx, r)
}
func (c *callerHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &callerHandler{
addSource: c.addSource,
next: c.next.WithAttrs(attrs),
}
}
func (c *callerHandler) WithGroup(group string) slog.Handler {
return &callerHandler{
addSource: c.addSource,
next: c.next.WithGroup(group),
}
}