Take the console location from the record (closes #36)
check / check (push) Successful in 30s
check / check (pull_request) Successful in 22s

ConsoleHandler found the file and line it prints by walking a fixed
number of stack frames up from itself, which only fit a record logged
through a slog.Logger and delivered through MultiplexHandler. It now
reads them from the record's PC, the call site slog stores, so a
ConsoleHandler used with slog.New and a record passed to Handle
directly print the right location too. A record whose PC is zero
prints ???:0 as before. The README drops its warning about the wrong
location and says how to set PC instead.

Model: opus-5-5
This commit is contained in:
2026-10-06 12:02:43 +00:00
parent 9b3d7326ce
commit 9710d3f05f
4 changed files with 116 additions and 11 deletions
+7 -9
View File
@@ -12,10 +12,6 @@ import (
"github.com/fatih/color"
)
// callerSkipFrames is the number of stack frames between runtime.Caller
// and the slog call site that produced the record.
const callerSkipFrames = 4
// ConsoleHandler writes human-readable, colored log lines to stdout.
type ConsoleHandler struct {
// out is where records are written. Nil means os.Stdout, looked up on
@@ -53,11 +49,13 @@ func (c *ConsoleHandler) Handle(
colorFunc = color.New(color.FgWhite).SprintfFunc()
}
// Get the caller information
_, file, line, ok := runtime.Caller(callerSkipFrames)
if !ok {
file = "???"
line = 0
// The file and line come from the record's PC, the call site; a record
// without one prints a placeholder.
file, line := "???", 0
if record.PC != 0 {
frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next()
file, line = frame.File, frame.Line
}
out := c.out