formatting_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package slogutil
  7. import (
  8. "bytes"
  9. "log/slog"
  10. "strings"
  11. "testing"
  12. "time"
  13. )
  14. func TestFormattingHandler(t *testing.T) {
  15. buf := new(bytes.Buffer)
  16. h := &formattingHandler{
  17. opts: &formattingOptions{
  18. LineFormat: DefaultLineFormat,
  19. out: buf,
  20. timeOverride: time.Unix(1234567890, 0).In(time.UTC),
  21. },
  22. }
  23. l := slog.New(h).With("a", "a")
  24. l.Info("A basic info line", "attr1", "val with spaces", "attr2", 2, "attr3", `val"quote`)
  25. l.Info("A basic info line", "attr1", "paren)thesis")
  26. l.Info("An info line with an empty value", "attr1", "")
  27. l.Info("An info line with grouped values", "attr1", "val1", slog.Group("foo", "attr2", 2, slog.Group("bar", "attr3", "3")))
  28. l2 := l.WithGroup("foo")
  29. l2.Info("An info line with grouped values via logger", "attr1", "val1", "attr2", 2)
  30. l3 := l2.WithGroup("bar")
  31. l3.Info("An info line with nested grouped values via logger", "attr1", "val1", "attr2", 2)
  32. l3.Debug("A debug entry")
  33. l3.Warn("A warning entry")
  34. l3.Error("An error")
  35. exp := `
  36. 2009-02-13 23:31:30 INF A basic info line (attr1="val with spaces" attr2=2 attr3="val\"quote" a=a log.pkg=slogutil)
  37. 2009-02-13 23:31:30 INF A basic info line (attr1="paren)thesis" a=a log.pkg=slogutil)
  38. 2009-02-13 23:31:30 INF An info line with an empty value (attr1="" a=a log.pkg=slogutil)
  39. 2009-02-13 23:31:30 INF An info line with grouped values (attr1=val1 foo.attr2=2 foo.bar.attr3=3 a=a log.pkg=slogutil)
  40. 2009-02-13 23:31:30 INF An info line with grouped values via logger (foo.attr1=val1 foo.attr2=2 a=a log.pkg=slogutil)
  41. 2009-02-13 23:31:30 INF An info line with nested grouped values via logger (bar.foo.attr1=val1 bar.foo.attr2=2 a=a log.pkg=slogutil)
  42. 2009-02-13 23:31:30 WRN A warning entry (a=a log.pkg=slogutil)
  43. 2009-02-13 23:31:30 ERR An error (a=a log.pkg=slogutil)`
  44. if strings.TrimSpace(buf.String()) != strings.TrimSpace(exp) {
  45. t.Log(buf.String())
  46. t.Log(exp)
  47. t.Error("mismatch")
  48. }
  49. }