Fix #7: implement AddSource flag, add as message

This commit is contained in:
2024-01-22 08:45:36 +01:00
committed by T.v.Dein
parent d53c1db7d0
commit 33798bddb3
3 changed files with 26 additions and 1 deletions

View File

@@ -35,6 +35,7 @@ func main() {
opts := &yadu.Options{ opts := &yadu.Options{
Level: slog.LevelDebug, Level: slog.LevelDebug,
ReplaceAttr: removeTime, ReplaceAttr: removeTime,
AddSource: true,
} }
logger := slog.New(yadu.NewHandler(os.Stdout, opts)) logger := slog.New(yadu.NewHandler(os.Stdout, opts))

View File

@@ -3,9 +3,11 @@ package yadu
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"io" "io"
"log/slog" "log/slog"
"regexp" "regexp"
"runtime"
"slices" "slices"
"strings" "strings"
"sync" "sync"
@@ -15,7 +17,7 @@ import (
"github.com/fatih/color" "github.com/fatih/color"
) )
const VERSION = "0.1.0" const VERSION = "0.1.1"
// We use RFC datestring by default // We use RFC datestring by default
const DefaultTimeFormat = "2006-01-02T03:04.05 MST" const DefaultTimeFormat = "2006-01-02T03:04.05 MST"
@@ -78,6 +80,11 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
}) })
tree := "" tree := ""
source := ""
if h.addSource && r.PC != 0 {
source = h.getSource(r.PC)
}
if len(h.attrs) > 0 { if len(h.attrs) > 0 {
bytetree, err := yaml.Marshal(h.attrs) 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(" ")
buf.WriteString(msg) buf.WriteString(msg)
buf.WriteString(" ") buf.WriteString(" ")
buf.WriteString(source)
buf.WriteString(" ")
buf.WriteString(color.WhiteString(tree)) buf.WriteString(color.WhiteString(tree))
buf.WriteString("\n") buf.WriteString("\n")
@@ -129,6 +138,13 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
return err 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 { func (h *Handler) Postprocess(yamlstr []byte) string {
return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(string(yamlstr), " ")) return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(string(yamlstr), " "))
} }

View File

@@ -115,6 +115,14 @@ var tests = []Tests{
Level: slog.LevelError, 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 // check if output is NOT colored when disabling it
name: "disable-color", name: "disable-color",