log_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package log
  2. import (
  3. "context"
  4. "testing"
  5. "go-common/library/net/metadata"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func initStdout() {
  9. conf := &Config{
  10. Stdout: true,
  11. }
  12. Init(conf)
  13. }
  14. func initFile() {
  15. conf := &Config{
  16. Dir: "/tmp",
  17. // VLevel: 2,
  18. Module: map[string]int32{"log_test": 1},
  19. }
  20. Init(conf)
  21. }
  22. func initAgent() {
  23. conf := &Config{
  24. Agent: &AgentConfig{
  25. TaskID: "000003",
  26. Addr: "172.16.0.204:514",
  27. Proto: "tcp",
  28. Chan: 1024,
  29. Buffer: 10,
  30. },
  31. }
  32. Init(conf)
  33. }
  34. type TestLog struct {
  35. A string
  36. B int
  37. C string
  38. D string
  39. }
  40. func testLog(t *testing.T) {
  41. t.Run("Error", func(t *testing.T) {
  42. Error("hello %s", "world")
  43. Errorv(context.Background(), KV("key", 2222222), KV("test2", "test"))
  44. })
  45. t.Run("Warn", func(t *testing.T) {
  46. Warn("hello %s", "world")
  47. Warnv(context.Background(), KV("key", 2222222), KV("test2", "test"))
  48. })
  49. t.Run("Info", func(t *testing.T) {
  50. Info("hello %s", "world")
  51. Infov(context.Background(), KV("key", 2222222), KV("test2", "test"))
  52. })
  53. }
  54. func TestLogAgent(t *testing.T) {
  55. initAgent()
  56. testLog(t)
  57. assert.Equal(t, nil, Close())
  58. }
  59. func TestFile(t *testing.T) {
  60. initFile()
  61. testLog(t)
  62. assert.Equal(t, nil, Close())
  63. }
  64. func TestStdout(t *testing.T) {
  65. initStdout()
  66. testLog(t)
  67. assert.Equal(t, nil, Close())
  68. }
  69. func TestLogW(t *testing.T) {
  70. D := logw([]interface{}{"i", "like", "a", "dog"})
  71. if len(D) != 2 || D[0].Key != "i" || D[0].Value != "like" || D[1].Key != "a" || D[1].Value != "dog" {
  72. t.Fatalf("logw out put should be ' {i like} {a dog}'")
  73. }
  74. D = logw([]interface{}{"i", "like", "dog"})
  75. if len(D) != 1 || D[0].Key != "i" || D[0].Value != "like" {
  76. t.Fatalf("logw out put should be ' {i like}'")
  77. }
  78. }
  79. func TestLogWithMirror(t *testing.T) {
  80. Info("test log")
  81. mdcontext := metadata.NewContext(context.Background(), metadata.MD{metadata.Mirror: "true"})
  82. Infov(mdcontext, KV("key1", "val1"), KV("key2", ""), KV("log", "log content"), KV("msg", "msg content"))
  83. mdcontext = metadata.NewContext(context.Background(), metadata.MD{metadata.Mirror: "***"})
  84. Infov(mdcontext, KV("key1", "val1"), KV("key2", ""), KV("log", "log content"), KV("msg", "msg content"))
  85. Infov(context.Background(), KV("key1", "val1"), KV("key2", ""), KV("log", "log content"), KV("msg", "msg content"))
  86. }