config_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package zap
  21. import (
  22. "os"
  23. "path/filepath"
  24. "sync/atomic"
  25. "testing"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/require"
  28. "go.uber.org/zap/zapcore"
  29. )
  30. func TestConfig(t *testing.T) {
  31. tests := []struct {
  32. desc string
  33. cfg Config
  34. expectN int64
  35. expectRe string
  36. }{
  37. {
  38. desc: "production",
  39. cfg: NewProductionConfig(),
  40. expectN: 2 + 100 + 1, // 2 from initial logs, 100 initial sampled logs, 1 from off-by-one in sampler
  41. expectRe: `{"level":"info","caller":"[a-z0-9_-]+/config_test.go:\d+","msg":"info","k":"v","z":"zz"}` + "\n" +
  42. `{"level":"warn","caller":"[a-z0-9_-]+/config_test.go:\d+","msg":"warn","k":"v","z":"zz"}` + "\n",
  43. },
  44. {
  45. desc: "development",
  46. cfg: NewDevelopmentConfig(),
  47. expectN: 3 + 200, // 3 initial logs, all 200 subsequent logs
  48. expectRe: "DEBUG\t[a-z0-9_-]+/config_test.go:" + `\d+` + "\tdebug\t" + `{"k": "v", "z": "zz"}` + "\n" +
  49. "INFO\t[a-z0-9_-]+/config_test.go:" + `\d+` + "\tinfo\t" + `{"k": "v", "z": "zz"}` + "\n" +
  50. "WARN\t[a-z0-9_-]+/config_test.go:" + `\d+` + "\twarn\t" + `{"k": "v", "z": "zz"}` + "\n" +
  51. `go.uber.org/zap.TestConfig.\w+`,
  52. },
  53. }
  54. for _, tt := range tests {
  55. t.Run(tt.desc, func(t *testing.T) {
  56. logOut := filepath.Join(t.TempDir(), "test.log")
  57. tt.cfg.OutputPaths = []string{logOut}
  58. tt.cfg.EncoderConfig.TimeKey = "" // no timestamps in tests
  59. tt.cfg.InitialFields = map[string]interface{}{"z": "zz", "k": "v"}
  60. hook, count := makeCountingHook()
  61. logger, err := tt.cfg.Build(Hooks(hook))
  62. require.NoError(t, err, "Unexpected error constructing logger.")
  63. logger.Debug("debug")
  64. logger.Info("info")
  65. logger.Warn("warn")
  66. byteContents, err := os.ReadFile(logOut)
  67. require.NoError(t, err, "Couldn't read log contents from temp file.")
  68. logs := string(byteContents)
  69. assert.Regexp(t, tt.expectRe, logs, "Unexpected log output.")
  70. for i := 0; i < 200; i++ {
  71. logger.Info("sampling")
  72. }
  73. assert.Equal(t, tt.expectN, count.Load(), "Hook called an unexpected number of times.")
  74. })
  75. }
  76. }
  77. func TestConfigWithInvalidPaths(t *testing.T) {
  78. tests := []struct {
  79. desc string
  80. output string
  81. errOutput string
  82. }{
  83. {"output directory doesn't exist", "/tmp/not-there/foo.log", "stderr"},
  84. {"error output directory doesn't exist", "stdout", "/tmp/not-there/foo-errors.log"},
  85. {"neither output directory exists", "/tmp/not-there/foo.log", "/tmp/not-there/foo-errors.log"},
  86. }
  87. for _, tt := range tests {
  88. t.Run(tt.desc, func(t *testing.T) {
  89. cfg := NewProductionConfig()
  90. cfg.OutputPaths = []string{tt.output}
  91. cfg.ErrorOutputPaths = []string{tt.errOutput}
  92. _, err := cfg.Build()
  93. assert.Error(t, err, "Expected an error opening a non-existent directory.")
  94. })
  95. }
  96. }
  97. func TestConfigWithMissingAttributes(t *testing.T) {
  98. tests := []struct {
  99. desc string
  100. cfg Config
  101. expectErr string
  102. }{
  103. {
  104. desc: "missing level",
  105. cfg: Config{
  106. Encoding: "json",
  107. },
  108. expectErr: "missing Level",
  109. },
  110. {
  111. desc: "missing encoder time in encoder config",
  112. cfg: Config{
  113. Level: NewAtomicLevelAt(zapcore.InfoLevel),
  114. Encoding: "json",
  115. EncoderConfig: zapcore.EncoderConfig{
  116. MessageKey: "msg",
  117. TimeKey: "ts",
  118. },
  119. },
  120. expectErr: "missing EncodeTime in EncoderConfig",
  121. },
  122. }
  123. for _, tt := range tests {
  124. t.Run(tt.desc, func(t *testing.T) {
  125. cfg := tt.cfg
  126. _, err := cfg.Build()
  127. assert.EqualError(t, err, tt.expectErr)
  128. })
  129. }
  130. }
  131. func makeSamplerCountingHook() (h func(zapcore.Entry, zapcore.SamplingDecision),
  132. dropped, sampled *atomic.Int64,
  133. ) {
  134. dropped = new(atomic.Int64)
  135. sampled = new(atomic.Int64)
  136. h = func(_ zapcore.Entry, dec zapcore.SamplingDecision) {
  137. if dec&zapcore.LogDropped > 0 {
  138. dropped.Add(1)
  139. } else if dec&zapcore.LogSampled > 0 {
  140. sampled.Add(1)
  141. }
  142. }
  143. return h, dropped, sampled
  144. }
  145. func TestConfigWithSamplingHook(t *testing.T) {
  146. shook, dcount, scount := makeSamplerCountingHook()
  147. cfg := Config{
  148. Level: NewAtomicLevelAt(InfoLevel),
  149. Development: false,
  150. Sampling: &SamplingConfig{
  151. Initial: 100,
  152. Thereafter: 100,
  153. Hook: shook,
  154. },
  155. Encoding: "json",
  156. EncoderConfig: NewProductionEncoderConfig(),
  157. OutputPaths: []string{"stderr"},
  158. ErrorOutputPaths: []string{"stderr"},
  159. }
  160. expectRe := `{"level":"info","caller":"[a-z0-9_-]+/config_test.go:\d+","msg":"info","k":"v","z":"zz"}` + "\n" +
  161. `{"level":"warn","caller":"[a-z0-9_-]+/config_test.go:\d+","msg":"warn","k":"v","z":"zz"}` + "\n"
  162. expectDropped := 99 // 200 - 100 initial - 1 thereafter
  163. expectSampled := 103 // 2 from initial + 100 + 1 thereafter
  164. logOut := filepath.Join(t.TempDir(), "test.log")
  165. cfg.OutputPaths = []string{logOut}
  166. cfg.EncoderConfig.TimeKey = "" // no timestamps in tests
  167. cfg.InitialFields = map[string]interface{}{"z": "zz", "k": "v"}
  168. logger, err := cfg.Build()
  169. require.NoError(t, err, "Unexpected error constructing logger.")
  170. logger.Debug("debug")
  171. logger.Info("info")
  172. logger.Warn("warn")
  173. byteContents, err := os.ReadFile(logOut)
  174. require.NoError(t, err, "Couldn't read log contents from temp file.")
  175. logs := string(byteContents)
  176. assert.Regexp(t, expectRe, logs, "Unexpected log output.")
  177. for i := 0; i < 200; i++ {
  178. logger.Info("sampling")
  179. }
  180. assert.Equal(t, int64(expectDropped), dcount.Load())
  181. assert.Equal(t, int64(expectSampled), scount.Load())
  182. }