journal/journslog/journslog_test.go

85 lines
2.0 KiB
Go

package journslog
import (
"log/slog"
"net/http"
"path/filepath"
"testing"
"src.lwithers.me.uk/go/journal"
"src.lwithers.me.uk/go/journal/testsink"
)
// TestHandler emits a log message with various attributes / groups and ensures
// the result is logged successfully.
func TestHandler(t *testing.T) {
sockpath := filepath.Join(t.TempDir(), "socket")
sink, err := testsink.New(sockpath)
if err != nil {
t.Fatal(err)
}
defer sink.Stop()
conn, err := journal.Connect(sockpath)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
jh, err := NewHandler(WithConn(conn))
if err != nil {
t.Fatal(err)
}
httpGroup := slog.Group("http", "path", "/foo", "status", http.StatusOK)
logger := slog.New(jh)
logger = logger.With("global_attr_key", "global_attr_val", httpGroup).WithGroup("app")
logger.Info("hello, journal", "slowkey", slowValue("slowval"), slog.Group("g1", "attr1", "val1", "attr2", 123))
msg, err := sink.Message(0)
if err != nil {
t.Fatal(err)
}
msgText, attrs, err := msg.Decode()
if err != nil {
t.Error(err)
}
if msgText != "hello, journal" {
t.Errorf("unexpected message text %q", msgText)
}
expAttrs := []testsink.DecodedAttr{
testsink.DecodedAttr{Key: "PRIORITY", Val: "6"},
testsink.DecodedAttr{Key: "GLOBAL_ATTR_KEY", Val: "global_attr_val"},
testsink.DecodedAttr{Key: "HTTP_PATH", Val: "/foo"},
testsink.DecodedAttr{Key: "HTTP_STATUS", Val: "200"},
testsink.DecodedAttr{Key: "APP_SLOWKEY", Val: "slowval"},
testsink.DecodedAttr{Key: "APP_G1_ATTR1", Val: "val1"},
testsink.DecodedAttr{Key: "APP_G1_ATTR2", Val: "123"},
}
for i := range expAttrs {
key := expAttrs[i].Key
val, ok := testsink.GetAttr(attrs, key)
switch {
case !ok:
t.Errorf("missing %s attribute", key)
case val != expAttrs[i].Val:
t.Errorf("unexpected %s value", key)
}
}
if t.Failed() {
for i := range attrs {
t.Errorf("attr %q=%q", attrs[i].Key, attrs[i].Val)
}
}
}
type slowValue string
func (s slowValue) LogValue() slog.Value {
return slog.StringValue(string(s))
}