sugar_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. "testing"
  23. "go.uber.org/zap/internal/exit"
  24. "go.uber.org/zap/internal/ztest"
  25. "go.uber.org/zap/zapcore"
  26. "go.uber.org/zap/zaptest/observer"
  27. "github.com/stretchr/testify/assert"
  28. "github.com/stretchr/testify/require"
  29. )
  30. func TestSugarWith(t *testing.T) {
  31. // Convenience functions to create expected error logs.
  32. ignored := func(msg interface{}) observer.LoggedEntry {
  33. return observer.LoggedEntry{
  34. Entry: zapcore.Entry{Level: DPanicLevel, Message: _oddNumberErrMsg},
  35. Context: []Field{Any("ignored", msg)},
  36. }
  37. }
  38. nonString := func(pairs ...invalidPair) observer.LoggedEntry {
  39. return observer.LoggedEntry{
  40. Entry: zapcore.Entry{Level: DPanicLevel, Message: _nonStringKeyErrMsg},
  41. Context: []Field{Array("invalid", invalidPairs(pairs))},
  42. }
  43. }
  44. tests := []struct {
  45. desc string
  46. args []interface{}
  47. expected []Field
  48. errLogs []observer.LoggedEntry
  49. }{
  50. {
  51. desc: "nil args",
  52. args: nil,
  53. expected: []Field{},
  54. errLogs: nil,
  55. },
  56. {
  57. desc: "empty slice of args",
  58. args: []interface{}{},
  59. expected: []Field{},
  60. errLogs: nil,
  61. },
  62. {
  63. desc: "just a dangling key",
  64. args: []interface{}{"should ignore"},
  65. expected: []Field{},
  66. errLogs: []observer.LoggedEntry{ignored("should ignore")},
  67. },
  68. {
  69. desc: "well-formed key-value pairs",
  70. args: []interface{}{"foo", 42, "true", "bar"},
  71. expected: []Field{Int("foo", 42), String("true", "bar")},
  72. errLogs: nil,
  73. },
  74. {
  75. desc: "just a structured field",
  76. args: []interface{}{Int("foo", 42)},
  77. expected: []Field{Int("foo", 42)},
  78. errLogs: nil,
  79. },
  80. {
  81. desc: "structured field and a dangling key",
  82. args: []interface{}{Int("foo", 42), "dangling"},
  83. expected: []Field{Int("foo", 42)},
  84. errLogs: []observer.LoggedEntry{ignored("dangling")},
  85. },
  86. {
  87. desc: "structured field and a dangling non-string key",
  88. args: []interface{}{Int("foo", 42), 13},
  89. expected: []Field{Int("foo", 42)},
  90. errLogs: []observer.LoggedEntry{ignored(13)},
  91. },
  92. {
  93. desc: "key-value pair and a dangling key",
  94. args: []interface{}{"foo", 42, "dangling"},
  95. expected: []Field{Int("foo", 42)},
  96. errLogs: []observer.LoggedEntry{ignored("dangling")},
  97. },
  98. {
  99. desc: "pairs, a structured field, and a dangling key",
  100. args: []interface{}{"first", "field", Int("foo", 42), "baz", "quux", "dangling"},
  101. expected: []Field{String("first", "field"), Int("foo", 42), String("baz", "quux")},
  102. errLogs: []observer.LoggedEntry{ignored("dangling")},
  103. },
  104. {
  105. desc: "one non-string key",
  106. args: []interface{}{"foo", 42, true, "bar"},
  107. expected: []Field{Int("foo", 42)},
  108. errLogs: []observer.LoggedEntry{nonString(invalidPair{2, true, "bar"})},
  109. },
  110. {
  111. desc: "pairs, structured fields, non-string keys, and a dangling key",
  112. args: []interface{}{"foo", 42, true, "bar", Int("structure", 11), 42, "reversed", "baz", "quux", "dangling"},
  113. expected: []Field{Int("foo", 42), Int("structure", 11), String("baz", "quux")},
  114. errLogs: []observer.LoggedEntry{
  115. ignored("dangling"),
  116. nonString(invalidPair{2, true, "bar"}, invalidPair{5, 42, "reversed"}),
  117. },
  118. },
  119. }
  120. for _, tt := range tests {
  121. withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  122. logger.With(tt.args...).Info("")
  123. output := logs.AllUntimed()
  124. if len(tt.errLogs) > 0 {
  125. for i := range tt.errLogs {
  126. assert.Equal(t, tt.errLogs[i], output[i], "Unexpected error log at position %d for scenario %s.", i, tt.desc)
  127. }
  128. }
  129. assert.Equal(t, len(tt.errLogs)+1, len(output), "Expected only one non-error message to be logged in scenario %s.", tt.desc)
  130. assert.Equal(t, tt.expected, output[len(tt.errLogs)].Context, "Unexpected message context in scenario %s.", tt.desc)
  131. })
  132. }
  133. }
  134. func TestSugarFieldsInvalidPairs(t *testing.T) {
  135. withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  136. logger.With(42, "foo", []string{"bar"}, "baz").Info("")
  137. output := logs.AllUntimed()
  138. // Double-check that the actual message was logged.
  139. require.Equal(t, 2, len(output), "Unexpected number of entries logged.")
  140. require.Equal(t, observer.LoggedEntry{Context: []Field{}}, output[1], "Unexpected non-error log entry.")
  141. // Assert that the error message's structured fields serialize properly.
  142. require.Equal(t, 1, len(output[0].Context), "Expected one field in error entry context.")
  143. enc := zapcore.NewMapObjectEncoder()
  144. output[0].Context[0].AddTo(enc)
  145. assert.Equal(t, []interface{}{
  146. map[string]interface{}{"position": int64(0), "key": int64(42), "value": "foo"},
  147. map[string]interface{}{"position": int64(2), "key": []interface{}{"bar"}, "value": "baz"},
  148. }, enc.Fields["invalid"], "Unexpected output when logging invalid key-value pairs.")
  149. })
  150. }
  151. func TestSugarStructuredLogging(t *testing.T) {
  152. tests := []struct {
  153. msg string
  154. expectMsg string
  155. }{
  156. {"foo", "foo"},
  157. {"", ""},
  158. }
  159. // Common to all test cases.
  160. context := []interface{}{"foo", "bar"}
  161. extra := []interface{}{"baz", false}
  162. expectedFields := []Field{String("foo", "bar"), Bool("baz", false)}
  163. for _, tt := range tests {
  164. withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  165. logger.With(context...).Debugw(tt.msg, extra...)
  166. logger.With(context...).Infow(tt.msg, extra...)
  167. logger.With(context...).Warnw(tt.msg, extra...)
  168. logger.With(context...).Errorw(tt.msg, extra...)
  169. logger.With(context...).DPanicw(tt.msg, extra...)
  170. expected := make([]observer.LoggedEntry, 5)
  171. for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
  172. expected[i] = observer.LoggedEntry{
  173. Entry: zapcore.Entry{Message: tt.expectMsg, Level: lvl},
  174. Context: expectedFields,
  175. }
  176. }
  177. assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
  178. })
  179. }
  180. }
  181. func TestSugarConcatenatingLogging(t *testing.T) {
  182. tests := []struct {
  183. args []interface{}
  184. expect string
  185. }{
  186. {[]interface{}{nil}, "<nil>"},
  187. }
  188. // Common to all test cases.
  189. context := []interface{}{"foo", "bar"}
  190. expectedFields := []Field{String("foo", "bar")}
  191. for _, tt := range tests {
  192. withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  193. logger.With(context...).Debug(tt.args...)
  194. logger.With(context...).Info(tt.args...)
  195. logger.With(context...).Warn(tt.args...)
  196. logger.With(context...).Error(tt.args...)
  197. logger.With(context...).DPanic(tt.args...)
  198. expected := make([]observer.LoggedEntry, 5)
  199. for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
  200. expected[i] = observer.LoggedEntry{
  201. Entry: zapcore.Entry{Message: tt.expect, Level: lvl},
  202. Context: expectedFields,
  203. }
  204. }
  205. assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
  206. })
  207. }
  208. }
  209. func TestSugarTemplatedLogging(t *testing.T) {
  210. tests := []struct {
  211. format string
  212. args []interface{}
  213. expect string
  214. }{
  215. {"", nil, ""},
  216. {"foo", nil, "foo"},
  217. // If the user fails to pass a template, degrade to fmt.Sprint.
  218. {"", []interface{}{"foo"}, "foo"},
  219. }
  220. // Common to all test cases.
  221. context := []interface{}{"foo", "bar"}
  222. expectedFields := []Field{String("foo", "bar")}
  223. for _, tt := range tests {
  224. withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  225. logger.With(context...).Debugf(tt.format, tt.args...)
  226. logger.With(context...).Infof(tt.format, tt.args...)
  227. logger.With(context...).Warnf(tt.format, tt.args...)
  228. logger.With(context...).Errorf(tt.format, tt.args...)
  229. logger.With(context...).DPanicf(tt.format, tt.args...)
  230. expected := make([]observer.LoggedEntry, 5)
  231. for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
  232. expected[i] = observer.LoggedEntry{
  233. Entry: zapcore.Entry{Message: tt.expect, Level: lvl},
  234. Context: expectedFields,
  235. }
  236. }
  237. assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
  238. })
  239. }
  240. }
  241. func TestSugarPanicLogging(t *testing.T) {
  242. tests := []struct {
  243. loggerLevel zapcore.Level
  244. f func(*SugaredLogger)
  245. expectedMsg string
  246. }{
  247. {FatalLevel, func(s *SugaredLogger) { s.Panic("foo") }, ""},
  248. {PanicLevel, func(s *SugaredLogger) { s.Panic("foo") }, "foo"},
  249. {DebugLevel, func(s *SugaredLogger) { s.Panic("foo") }, "foo"},
  250. {FatalLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, ""},
  251. {PanicLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, "foo"},
  252. {DebugLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, "foo"},
  253. {FatalLevel, func(s *SugaredLogger) { s.Panicw("foo") }, ""},
  254. {PanicLevel, func(s *SugaredLogger) { s.Panicw("foo") }, "foo"},
  255. {DebugLevel, func(s *SugaredLogger) { s.Panicw("foo") }, "foo"},
  256. }
  257. for _, tt := range tests {
  258. withSugar(t, tt.loggerLevel, nil, func(sugar *SugaredLogger, logs *observer.ObservedLogs) {
  259. assert.Panics(t, func() { tt.f(sugar) }, "Expected panic-level logger calls to panic.")
  260. if tt.expectedMsg != "" {
  261. assert.Equal(t, []observer.LoggedEntry{{
  262. Context: []Field{},
  263. Entry: zapcore.Entry{Message: tt.expectedMsg, Level: PanicLevel},
  264. }}, logs.AllUntimed(), "Unexpected log output.")
  265. } else {
  266. assert.Equal(t, 0, logs.Len(), "Didn't expect any log output.")
  267. }
  268. })
  269. }
  270. }
  271. func TestSugarFatalLogging(t *testing.T) {
  272. tests := []struct {
  273. loggerLevel zapcore.Level
  274. f func(*SugaredLogger)
  275. expectedMsg string
  276. }{
  277. {FatalLevel + 1, func(s *SugaredLogger) { s.Fatal("foo") }, ""},
  278. {FatalLevel, func(s *SugaredLogger) { s.Fatal("foo") }, "foo"},
  279. {DebugLevel, func(s *SugaredLogger) { s.Fatal("foo") }, "foo"},
  280. {FatalLevel + 1, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, ""},
  281. {FatalLevel, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, "foo"},
  282. {DebugLevel, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, "foo"},
  283. {FatalLevel + 1, func(s *SugaredLogger) { s.Fatalw("foo") }, ""},
  284. {FatalLevel, func(s *SugaredLogger) { s.Fatalw("foo") }, "foo"},
  285. {DebugLevel, func(s *SugaredLogger) { s.Fatalw("foo") }, "foo"},
  286. }
  287. for _, tt := range tests {
  288. withSugar(t, tt.loggerLevel, nil, func(sugar *SugaredLogger, logs *observer.ObservedLogs) {
  289. stub := exit.WithStub(func() { tt.f(sugar) })
  290. assert.True(t, stub.Exited, "Expected all calls to fatal logger methods to exit process.")
  291. if tt.expectedMsg != "" {
  292. assert.Equal(t, []observer.LoggedEntry{{
  293. Context: []Field{},
  294. Entry: zapcore.Entry{Message: tt.expectedMsg, Level: FatalLevel},
  295. }}, logs.AllUntimed(), "Unexpected log output.")
  296. } else {
  297. assert.Equal(t, 0, logs.Len(), "Didn't expect any log output.")
  298. }
  299. })
  300. }
  301. }
  302. func TestSugarAddCaller(t *testing.T) {
  303. tests := []struct {
  304. options []Option
  305. pat string
  306. }{
  307. {opts(AddCaller()), `.+/sugar_test.go:[\d]+$`},
  308. {opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(-1)), `.+/zap/sugar_test.go:[\d]+$`},
  309. {opts(AddCaller(), AddCallerSkip(1)), `.+/zap/common_test.go:[\d]+$`},
  310. {opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(5)), `.+/src/runtime/.*:[\d]+$`},
  311. }
  312. for _, tt := range tests {
  313. withSugar(t, DebugLevel, tt.options, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
  314. logger.Info("")
  315. output := logs.AllUntimed()
  316. assert.Equal(t, 1, len(output), "Unexpected number of logs written out.")
  317. assert.Regexp(
  318. t,
  319. tt.pat,
  320. output[0].Entry.Caller,
  321. "Expected to find package name and file name in output.",
  322. )
  323. })
  324. }
  325. }
  326. func TestSugarAddCallerFail(t *testing.T) {
  327. errBuf := &ztest.Buffer{}
  328. withSugar(t, DebugLevel, opts(AddCaller(), AddCallerSkip(1e3), ErrorOutput(errBuf)), func(log *SugaredLogger, logs *observer.ObservedLogs) {
  329. log.Info("Failure.")
  330. assert.Regexp(
  331. t,
  332. `Logger.check error: failed to get caller`,
  333. errBuf.String(),
  334. "Didn't find expected failure message.",
  335. )
  336. assert.Equal(
  337. t,
  338. logs.AllUntimed()[0].Entry.Message,
  339. "Failure.",
  340. "Expected original message to survive failures in runtime.Caller.")
  341. })
  342. }