feat(applog): add JSON logger and context helpers
This commit is contained in:
54
backend/internal/applog/applog_test.go
Normal file
54
backend/internal/applog/applog_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package applog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewLogger_FiltersBelowConfiguredLevel(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
logger := NewLogger("warn", &buf)
|
||||
|
||||
logger.Info("should be dropped")
|
||||
if buf.Len() != 0 {
|
||||
t.Fatalf("expected no output for an Info message under a warn-level logger, got %q", buf.String())
|
||||
}
|
||||
|
||||
logger.Warn("should appear")
|
||||
if !strings.Contains(buf.String(), "should appear") {
|
||||
t.Fatalf("expected the Warn message in output, got %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLogger_WritesValidJSON(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
logger := NewLogger("info", &buf)
|
||||
logger.Info("hello", "key", "value")
|
||||
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(buf.Bytes(), &decoded); err != nil {
|
||||
t.Fatalf("output is not valid JSON: %v (%q)", err, buf.String())
|
||||
}
|
||||
if decoded["msg"] != "hello" || decoded["key"] != "value" {
|
||||
t.Errorf("decoded = %+v, want msg=hello key=value", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithLogger_FromContext_RoundTrip(t *testing.T) {
|
||||
logger := slog.New(slog.NewJSONHandler(&bytes.Buffer{}, nil))
|
||||
ctx := WithLogger(context.Background(), logger)
|
||||
|
||||
if got := FromContext(ctx); got != logger {
|
||||
t.Errorf("FromContext returned a different logger than what was stashed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromContext_DefaultsWhenNoneSet(t *testing.T) {
|
||||
if got := FromContext(context.Background()); got == nil {
|
||||
t.Fatal("FromContext on a bare context returned nil, want slog.Default()")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user