simplelog/console_handler.go
sneak 3a94b5e22a aider: Include filename and line number in console logger output.
# Aider chat conversation:

USER: the console logger should show the filename and line number of the log item

ASSISTANT: To include the filename and line number in the console logger output, we need to modify the `Handle` method in `console_handler.go` to extract and display this information.

Here is the *SEARCH/REPLACE* block:

console_handler.go
```go
<<<<<<< SEARCH
	fmt.Println(colorFunc("%s [%s] %s", timestamp, record.Level, record.Message))
=======
	// 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))
>>>>>>> REPLACE
```
2024-05-14 05:17:08 -07:00

50 lines
1.1 KiB
Go

package simplelog
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/fatih/color"
)
type ConsoleHandler struct{}
func NewConsoleHandler() *ConsoleHandler {
return &ConsoleHandler{}
}
func (c *ConsoleHandler) Handle(ctx context.Context, record slog.Record) error {
timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z07:00")
var colorFunc func(format string, a ...interface{}) string
switch record.Level {
case slog.LevelInfo:
colorFunc = color.New(color.FgBlue).SprintfFunc()
case slog.LevelWarn:
colorFunc = color.New(color.FgYellow).SprintfFunc()
case slog.LevelError:
colorFunc = color.New(color.FgRed).SprintfFunc()
default:
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))
return nil
}
func (c *ConsoleHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (c *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return c
}
func (c *ConsoleHandler) WithGroup(name string) slog.Handler {
return c
}