log_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package log_test
  2. import (
  3. "bytes"
  4. "github.com/stretchr/testify/require"
  5. "heckel.io/ntfy/log"
  6. "net/http"
  7. "os"
  8. "testing"
  9. "time"
  10. )
  11. func TestMain(m *testing.M) {
  12. exitCode := m.Run()
  13. resetState()
  14. log.SetLevel(log.ErrorLevel) // For other modules!
  15. os.Exit(exitCode)
  16. }
  17. func TestLog_TagContextFieldFields(t *testing.T) {
  18. t.Cleanup(resetState)
  19. v := &fakeVisitor{
  20. UserID: "u_abc",
  21. IP: "1.2.3.4",
  22. }
  23. var out bytes.Buffer
  24. log.SetOutput(&out)
  25. log.SetFormat(log.JSONFormat)
  26. log.SetLevelOverride("tag", "stripe", log.DebugLevel)
  27. log.
  28. Tag("mytag").
  29. Field("field2", 123).
  30. Field("field1", "value1").
  31. Time(time.Unix(123, 0)).
  32. Info("hi there %s", "phil")
  33. log.
  34. Tag("not-stripe").
  35. Debug("this message will not appear")
  36. log.
  37. With(v).
  38. Fields(log.Context{
  39. "stripe_customer_id": "acct_123",
  40. "stripe_subscription_id": "sub_123",
  41. }).
  42. Tag("stripe").
  43. Err(http.ErrHandlerTimeout).
  44. Time(time.Unix(456, 0)).
  45. Debug("Subscription status %s", "active")
  46. expected := `{"time":123000,"level":"INFO","message":"hi there phil","field1":"value1","field2":123,"tag":"mytag"}
  47. {"time":456000,"level":"DEBUG","message":"Subscription status active","error":"http: Handler timeout","stripe_customer_id":"acct_123","stripe_subscription_id":"sub_123","tag":"stripe","user_id":"u_abc","visitor_ip":"1.2.3.4"}
  48. `
  49. require.Equal(t, expected, out.String())
  50. }
  51. type fakeVisitor struct {
  52. UserID string
  53. IP string
  54. }
  55. func (v *fakeVisitor) Context() log.Context {
  56. return map[string]any{
  57. "user_id": v.UserID,
  58. "visitor_ip": v.IP,
  59. }
  60. }
  61. func resetState() {
  62. log.SetLevel(log.DefaultLevel)
  63. log.SetFormat(log.DefaultFormat)
  64. log.SetOutput(log.DefaultOutput)
  65. log.ResetLevelOverrides()
  66. }