From 33798bddb356449bc3e7581a7e0faa7484e790ae Mon Sep 17 00:00:00 2001 From: Thomas von Dein Date: Mon, 22 Jan 2024 08:45:36 +0100 Subject: [PATCH] Fix #7: implement AddSource flag, add as message --- example/example.go | 1 + handler.go | 18 +++++++++++++++++- handler_test.go | 8 ++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/example/example.go b/example/example.go index 1773094..a4d7d98 100644 --- a/example/example.go +++ b/example/example.go @@ -35,6 +35,7 @@ func main() { opts := &yadu.Options{ Level: slog.LevelDebug, ReplaceAttr: removeTime, + AddSource: true, } logger := slog.New(yadu.NewHandler(os.Stdout, opts)) diff --git a/handler.go b/handler.go index 465d0fb..d2391e5 100644 --- a/handler.go +++ b/handler.go @@ -3,9 +3,11 @@ package yadu import ( "bytes" "context" + "fmt" "io" "log/slog" "regexp" + "runtime" "slices" "strings" "sync" @@ -15,7 +17,7 @@ import ( "github.com/fatih/color" ) -const VERSION = "0.1.0" +const VERSION = "0.1.1" // We use RFC datestring by default const DefaultTimeFormat = "2006-01-02T03:04.05 MST" @@ -78,6 +80,11 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error { }) tree := "" + source := "" + + if h.addSource && r.PC != 0 { + source = h.getSource(r.PC) + } if len(h.attrs) > 0 { bytetree, err := yaml.Marshal(h.attrs) @@ -119,6 +126,8 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error { buf.WriteString(" ") buf.WriteString(msg) buf.WriteString(" ") + buf.WriteString(source) + buf.WriteString(" ") buf.WriteString(color.WhiteString(tree)) buf.WriteString("\n") @@ -129,6 +138,13 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error { return err } +// report caller source+line as yaml string +func (h *Handler) getSource(pc uintptr) string { + fs := runtime.CallersFrames([]uintptr{pc}) + source, _ := fs.Next() + return fmt.Sprintf("%s: %d", source.File, source.Line) +} + func (h *Handler) Postprocess(yamlstr []byte) string { return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(string(yamlstr), " ")) } diff --git a/handler_test.go b/handler_test.go index bb57051..578c4d0 100644 --- a/handler_test.go +++ b/handler_test.go @@ -115,6 +115,14 @@ var tests = []Tests{ Level: slog.LevelError, }, }, + { + name: "has-source", + want: "handler_test.go", + negate: false, + opts: yadu.Options{ + AddSource: true, + }, + }, { // check if output is NOT colored when disabling it name: "disable-color",