go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

commit 2befd169e9fcbb1f84d94ebd711f85be964a717c
parent fd3db37d26269c3b57eaa192bcaa11c7fbb156f6
Author: lash <dev@holbrook.no>
Date:   Fri,  3 Jan 2025 08:49:47 +0000

Add custom context key in slogging

Signed-off-by: lash <dev@holbrook.no>

Diffstat:
Mlogging/vanilla.go | 23+++++++++++++++++++----
Mlogging/vanilla_test.go | 18++++++++++++++++++
2 files changed, 37 insertions(+), 4 deletions(-)

diff --git a/logging/vanilla.go b/logging/vanilla.go @@ -11,13 +11,14 @@ import ( var ( // LogWriter is used as io.Writer the Vanilla Logger implementation. - LogWriter = os.Stderr + LogWriter io.Writer = os.Stderr ) // Vanilla is a basic single-line structured output logger for terminal output. type Vanilla struct { domain string levelFilter int + ctxkey []string } // NewVanilla creates a new Vanilla logger. @@ -40,6 +41,11 @@ func (v Vanilla) WithLevel(level int) Vanilla { return v } +func (v Vanilla) WithContextKey(k string) Vanilla { + v.ctxkey = append(v.ctxkey, k) + return v +} + // Printf logs to the global writer. func (v Vanilla) Printf(level int, msg string, args ...any) { v.Writef(LogWriter, level, msg, args...) @@ -52,9 +58,9 @@ func (v Vanilla) writef(ctx context.Context, w io.Writer, file string, line int, return } if ctx == nil { - argsStr = argsToString(nil, args) + argsStr = v.argsToString(nil, args) } else { - argsStr = argsToString(ctx, args) + argsStr = v.argsToString(ctx, args) } if len(msg) > 0 { @@ -153,7 +159,7 @@ func getCaller(depth int) (string, int) { } // string representation of the given structured log args. -func argsToString(ctx context.Context, args []any) string { +func (v Vanilla) argsToString(ctx context.Context, args []any) string { var s string if ctx != nil { @@ -162,6 +168,15 @@ func argsToString(ctx context.Context, args []any) string { args = append(args, "session-id", sessionId) } } + for _, k := range(v.ctxkey) { + v := ctx.Value(k) + if v != nil { + v, ok := v.(string) + if ok { + args = append(args, "x-" + k, v) + } + } + } c := len(args) var i int for i = 0; i < c; i += 2 { diff --git a/logging/vanilla_test.go b/logging/vanilla_test.go @@ -2,6 +2,8 @@ package logging import ( "bytes" + "context" + "strings" "testing" ) @@ -18,3 +20,19 @@ func TestVanilla(t *testing.T) { t.Errorf("expected output") } } + +func TestVanillaCtx(t *testing.T) { + logg := NewVanilla().WithDomain("test").WithLevel(LVL_DEBUG).WithContextKey("foo") + ctx := context.WithValue(context.Background(), "foo", "bar") + w := bytes.NewBuffer(nil) + LogWriter = w + + logg.DebugCtxf(ctx, "message", "xyzzy", 666, "inky", "pinky") + s := string(w.Bytes()) + if len(s) == 0 { + t.Errorf("expected output") + } + if !strings.Contains(s, "foo=bar") { + t.Errorf("expected 'foo=bar' in output, output was: %s", s) + } +}