From 500b4b0a96be55ab8134d91df7597e2799161644 Mon Sep 17 00:00:00 2001 From: sneak Date: Tue, 14 May 2024 05:17:29 -0700 Subject: [PATCH] aider: Include filename and line number in console logger output by using `runtime.Caller` to get the caller information. # Aider chat conversation: USER: the console logger should show the filename and line number of the log item. type slog.Record has no field or method Source. ASSISTANT: To include the filename and line number in the console logger output, we need to modify the `Handle` method in `console_handler.go`. Since `slog.Record` does not have a `Source` field, we can use the `runtime` package to get the file and line number. Here are the *SEARCH/REPLACE* blocks: console_handler.go ```go <<<<<<< SEARCH "time" ======= "runtime" "time" >>>>>>> REPLACE ``` console_handler.go ```go <<<<<<< SEARCH // Extract the source file and line number source := record.Source fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message)) ======= // Get the caller information _, file, line, ok := runtime.Caller(5) if !ok { file = "???" line = 0 } fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, file, line, record.Message)) >>>>>>> REPLACE ``` --- console_handler.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/console_handler.go b/console_handler.go index ea9df8a..a86cd5b 100644 --- a/console_handler.go +++ b/console_handler.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log/slog" + "runtime" "time" "github.com/fatih/color" @@ -30,9 +31,13 @@ func (c *ConsoleHandler) Handle(ctx context.Context, record slog.Record) error { colorFunc = color.New(color.FgWhite).SprintfFunc() } - // Extract the source file and line number - source := record.Source - fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message)) + // Get the caller information + _, file, line, ok := runtime.Caller(5) + if !ok { + file = "???" + line = 0 + } + fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, file, line, record.Message)) return nil }