logrus_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. package logrus_test
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. . "github.com/sirupsen/logrus"
  14. . "github.com/sirupsen/logrus/internal/testutils"
  15. )
  16. // TestReportCaller verifies that when ReportCaller is set, the 'func' field
  17. // is added, and when it is unset it is not set or modified
  18. // Verify that functions within the Logrus package aren't considered when
  19. // discovering the caller.
  20. func TestReportCallerWhenConfigured(t *testing.T) {
  21. LogAndAssertJSON(t, func(log *Logger) {
  22. log.ReportCaller = false
  23. log.Print("testNoCaller")
  24. }, func(fields Fields) {
  25. assert.Equal(t, "testNoCaller", fields["msg"])
  26. assert.Equal(t, "info", fields["level"])
  27. assert.Equal(t, nil, fields["func"])
  28. })
  29. LogAndAssertJSON(t, func(log *Logger) {
  30. log.ReportCaller = true
  31. log.Print("testWithCaller")
  32. }, func(fields Fields) {
  33. assert.Equal(t, "testWithCaller", fields["msg"])
  34. assert.Equal(t, "info", fields["level"])
  35. assert.Equal(t,
  36. "github.com/sirupsen/logrus_test.TestReportCallerWhenConfigured.func3", fields["func"])
  37. })
  38. }
  39. func logSomething(t *testing.T, message string) Fields {
  40. var buffer bytes.Buffer
  41. var fields Fields
  42. logger := New()
  43. logger.Out = &buffer
  44. logger.Formatter = new(JSONFormatter)
  45. logger.ReportCaller = true
  46. entry := logger.WithFields(Fields{
  47. "foo": "bar",
  48. })
  49. entry.Info(message)
  50. err := json.Unmarshal(buffer.Bytes(), &fields)
  51. assert.Nil(t, err)
  52. return fields
  53. }
  54. // TestReportCallerHelperDirect - verify reference when logging from a regular function
  55. func TestReportCallerHelperDirect(t *testing.T) {
  56. fields := logSomething(t, "direct")
  57. assert.Equal(t, "direct", fields["msg"])
  58. assert.Equal(t, "info", fields["level"])
  59. assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])
  60. }
  61. // TestReportCallerHelperDirect - verify reference when logging from a function called via pointer
  62. func TestReportCallerHelperViaPointer(t *testing.T) {
  63. fptr := logSomething
  64. fields := fptr(t, "via pointer")
  65. assert.Equal(t, "via pointer", fields["msg"])
  66. assert.Equal(t, "info", fields["level"])
  67. assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])
  68. }
  69. func TestPrint(t *testing.T) {
  70. LogAndAssertJSON(t, func(log *Logger) {
  71. log.Print("test")
  72. }, func(fields Fields) {
  73. assert.Equal(t, "test", fields["msg"])
  74. assert.Equal(t, "info", fields["level"])
  75. })
  76. }
  77. func TestInfo(t *testing.T) {
  78. LogAndAssertJSON(t, func(log *Logger) {
  79. log.Info("test")
  80. }, func(fields Fields) {
  81. assert.Equal(t, "test", fields["msg"])
  82. assert.Equal(t, "info", fields["level"])
  83. })
  84. }
  85. func TestWarn(t *testing.T) {
  86. LogAndAssertJSON(t, func(log *Logger) {
  87. log.Warn("test")
  88. }, func(fields Fields) {
  89. assert.Equal(t, "test", fields["msg"])
  90. assert.Equal(t, "warning", fields["level"])
  91. })
  92. }
  93. func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
  94. LogAndAssertJSON(t, func(log *Logger) {
  95. log.Infoln("test", "test")
  96. }, func(fields Fields) {
  97. assert.Equal(t, "test test", fields["msg"])
  98. })
  99. }
  100. func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
  101. LogAndAssertJSON(t, func(log *Logger) {
  102. log.Infoln("test", 10)
  103. }, func(fields Fields) {
  104. assert.Equal(t, "test 10", fields["msg"])
  105. })
  106. }
  107. func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
  108. LogAndAssertJSON(t, func(log *Logger) {
  109. log.Infoln(10, 10)
  110. }, func(fields Fields) {
  111. assert.Equal(t, "10 10", fields["msg"])
  112. })
  113. }
  114. func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
  115. LogAndAssertJSON(t, func(log *Logger) {
  116. log.Infoln(10, 10)
  117. }, func(fields Fields) {
  118. assert.Equal(t, "10 10", fields["msg"])
  119. })
  120. }
  121. func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
  122. LogAndAssertJSON(t, func(log *Logger) {
  123. log.Info("test", 10)
  124. }, func(fields Fields) {
  125. assert.Equal(t, "test10", fields["msg"])
  126. })
  127. }
  128. func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
  129. LogAndAssertJSON(t, func(log *Logger) {
  130. log.Info("test", "test")
  131. }, func(fields Fields) {
  132. assert.Equal(t, "testtest", fields["msg"])
  133. })
  134. }
  135. func TestWithFieldsShouldAllowAssignments(t *testing.T) {
  136. var buffer bytes.Buffer
  137. var fields Fields
  138. logger := New()
  139. logger.Out = &buffer
  140. logger.Formatter = new(JSONFormatter)
  141. localLog := logger.WithFields(Fields{
  142. "key1": "value1",
  143. })
  144. localLog.WithField("key2", "value2").Info("test")
  145. err := json.Unmarshal(buffer.Bytes(), &fields)
  146. assert.Nil(t, err)
  147. assert.Equal(t, "value2", fields["key2"])
  148. assert.Equal(t, "value1", fields["key1"])
  149. buffer = bytes.Buffer{}
  150. fields = Fields{}
  151. localLog.Info("test")
  152. err = json.Unmarshal(buffer.Bytes(), &fields)
  153. assert.Nil(t, err)
  154. _, ok := fields["key2"]
  155. assert.Equal(t, false, ok)
  156. assert.Equal(t, "value1", fields["key1"])
  157. }
  158. func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
  159. LogAndAssertJSON(t, func(log *Logger) {
  160. log.WithField("msg", "hello").Info("test")
  161. }, func(fields Fields) {
  162. assert.Equal(t, "test", fields["msg"])
  163. })
  164. }
  165. func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
  166. LogAndAssertJSON(t, func(log *Logger) {
  167. log.WithField("msg", "hello").Info("test")
  168. }, func(fields Fields) {
  169. assert.Equal(t, "test", fields["msg"])
  170. assert.Equal(t, "hello", fields["fields.msg"])
  171. })
  172. }
  173. func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
  174. LogAndAssertJSON(t, func(log *Logger) {
  175. log.WithField("time", "hello").Info("test")
  176. }, func(fields Fields) {
  177. assert.Equal(t, "hello", fields["fields.time"])
  178. })
  179. }
  180. func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
  181. LogAndAssertJSON(t, func(log *Logger) {
  182. log.WithField("level", 1).Info("test")
  183. }, func(fields Fields) {
  184. assert.Equal(t, "info", fields["level"])
  185. assert.Equal(t, 1.0, fields["fields.level"]) // JSON has floats only
  186. })
  187. }
  188. func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
  189. LogAndAssertText(t, func(log *Logger) {
  190. ll := log.WithField("herp", "derp")
  191. ll.Info("hello")
  192. ll.Info("bye")
  193. }, func(fields map[string]string) {
  194. for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
  195. if _, ok := fields[fieldName]; ok {
  196. t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
  197. }
  198. }
  199. })
  200. }
  201. func TestWithTimeShouldOverrideTime(t *testing.T) {
  202. now := time.Now().Add(24 * time.Hour)
  203. LogAndAssertJSON(t, func(log *Logger) {
  204. log.WithTime(now).Info("foobar")
  205. }, func(fields Fields) {
  206. assert.Equal(t, fields["time"], now.Format(time.RFC3339))
  207. })
  208. }
  209. func TestWithTimeShouldNotOverrideFields(t *testing.T) {
  210. now := time.Now().Add(24 * time.Hour)
  211. LogAndAssertJSON(t, func(log *Logger) {
  212. log.WithField("herp", "derp").WithTime(now).Info("blah")
  213. }, func(fields Fields) {
  214. assert.Equal(t, fields["time"], now.Format(time.RFC3339))
  215. assert.Equal(t, fields["herp"], "derp")
  216. })
  217. }
  218. func TestWithFieldShouldNotOverrideTime(t *testing.T) {
  219. now := time.Now().Add(24 * time.Hour)
  220. LogAndAssertJSON(t, func(log *Logger) {
  221. log.WithTime(now).WithField("herp", "derp").Info("blah")
  222. }, func(fields Fields) {
  223. assert.Equal(t, fields["time"], now.Format(time.RFC3339))
  224. assert.Equal(t, fields["herp"], "derp")
  225. })
  226. }
  227. func TestTimeOverrideMultipleLogs(t *testing.T) {
  228. var buffer bytes.Buffer
  229. var firstFields, secondFields Fields
  230. logger := New()
  231. logger.Out = &buffer
  232. formatter := new(JSONFormatter)
  233. formatter.TimestampFormat = time.StampMilli
  234. logger.Formatter = formatter
  235. llog := logger.WithField("herp", "derp")
  236. llog.Info("foo")
  237. err := json.Unmarshal(buffer.Bytes(), &firstFields)
  238. assert.NoError(t, err, "should have decoded first message")
  239. buffer.Reset()
  240. time.Sleep(10 * time.Millisecond)
  241. llog.Info("bar")
  242. err = json.Unmarshal(buffer.Bytes(), &secondFields)
  243. assert.NoError(t, err, "should have decoded second message")
  244. assert.NotEqual(t, firstFields["time"], secondFields["time"], "timestamps should not be equal")
  245. }
  246. func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
  247. var buffer bytes.Buffer
  248. var fields Fields
  249. logger := New()
  250. logger.Out = &buffer
  251. logger.Formatter = new(JSONFormatter)
  252. llog := logger.WithField("context", "eating raw fish")
  253. llog.Info("looks delicious")
  254. err := json.Unmarshal(buffer.Bytes(), &fields)
  255. assert.NoError(t, err, "should have decoded first message")
  256. assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
  257. assert.Equal(t, fields["msg"], "looks delicious")
  258. assert.Equal(t, fields["context"], "eating raw fish")
  259. buffer.Reset()
  260. llog.Warn("omg it is!")
  261. err = json.Unmarshal(buffer.Bytes(), &fields)
  262. assert.NoError(t, err, "should have decoded second message")
  263. assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
  264. assert.Equal(t, "omg it is!", fields["msg"])
  265. assert.Equal(t, "eating raw fish", fields["context"])
  266. assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
  267. }
  268. func TestNestedLoggingReportsCorrectCaller(t *testing.T) {
  269. var buffer bytes.Buffer
  270. var fields Fields
  271. logger := New()
  272. logger.Out = &buffer
  273. logger.Formatter = new(JSONFormatter)
  274. logger.ReportCaller = true
  275. llog := logger.WithField("context", "eating raw fish")
  276. llog.Info("looks delicious")
  277. err := json.Unmarshal(buffer.Bytes(), &fields)
  278. require.NoError(t, err, "should have decoded first message")
  279. assert.Equal(t, 6, len(fields), "should have msg/time/level/func/context fields")
  280. assert.Equal(t, "looks delicious", fields["msg"])
  281. assert.Equal(t, "eating raw fish", fields["context"])
  282. assert.Equal(t,
  283. "github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])
  284. cwd, err := os.Getwd()
  285. require.NoError(t, err)
  286. assert.Equal(t, filepath.ToSlash(cwd+"/logrus_test.go:340"), filepath.ToSlash(fields["file"].(string)))
  287. buffer.Reset()
  288. logger.WithFields(Fields{
  289. "Clyde": "Stubblefield",
  290. }).WithFields(Fields{
  291. "Jab'o": "Starks",
  292. }).WithFields(Fields{
  293. "uri": "https://www.youtube.com/watch?v=V5DTznu-9v0",
  294. }).WithFields(Fields{
  295. "func": "y drummer",
  296. }).WithFields(Fields{
  297. "James": "Brown",
  298. }).Print("The hardest workin' man in show business")
  299. err = json.Unmarshal(buffer.Bytes(), &fields)
  300. assert.NoError(t, err, "should have decoded second message")
  301. assert.Equal(t, 11, len(fields), "should have all builtin fields plus foo,bar,baz,...")
  302. assert.Equal(t, "Stubblefield", fields["Clyde"])
  303. assert.Equal(t, "Starks", fields["Jab'o"])
  304. assert.Equal(t, "https://www.youtube.com/watch?v=V5DTznu-9v0", fields["uri"])
  305. assert.Equal(t, "y drummer", fields["fields.func"])
  306. assert.Equal(t, "Brown", fields["James"])
  307. assert.Equal(t, "The hardest workin' man in show business", fields["msg"])
  308. assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
  309. assert.Equal(t,
  310. "github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])
  311. require.NoError(t, err)
  312. assert.Equal(t, filepath.ToSlash(cwd+"/logrus_test.go:365"), filepath.ToSlash(fields["file"].(string)))
  313. logger.ReportCaller = false // return to default value
  314. }
  315. func logLoop(iterations int, reportCaller bool) {
  316. var buffer bytes.Buffer
  317. logger := New()
  318. logger.Out = &buffer
  319. logger.Formatter = new(JSONFormatter)
  320. logger.ReportCaller = reportCaller
  321. for i := 0; i < iterations; i++ {
  322. logger.Infof("round %d of %d", i, iterations)
  323. }
  324. }
  325. // Assertions for upper bounds to reporting overhead
  326. func TestCallerReportingOverhead(t *testing.T) {
  327. iterations := 5000
  328. before := time.Now()
  329. logLoop(iterations, false)
  330. during := time.Now()
  331. logLoop(iterations, true)
  332. after := time.Now()
  333. elapsedNotReporting := during.Sub(before).Nanoseconds()
  334. elapsedReporting := after.Sub(during).Nanoseconds()
  335. maxDelta := 1 * time.Second
  336. assert.WithinDuration(t, during, before, maxDelta,
  337. "%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",
  338. iterations, maxDelta.Seconds(), elapsedNotReporting)
  339. assert.WithinDuration(t, after, during, maxDelta,
  340. "%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",
  341. iterations, maxDelta.Seconds(), elapsedReporting)
  342. }
  343. // benchmarks for both with and without caller-function reporting
  344. func BenchmarkWithoutCallerTracing(b *testing.B) {
  345. for i := 0; i < b.N; i++ {
  346. logLoop(1000, false)
  347. }
  348. }
  349. func BenchmarkWithCallerTracing(b *testing.B) {
  350. for i := 0; i < b.N; i++ {
  351. logLoop(1000, true)
  352. }
  353. }
  354. func TestConvertLevelToString(t *testing.T) {
  355. assert.Equal(t, "trace", TraceLevel.String())
  356. assert.Equal(t, "debug", DebugLevel.String())
  357. assert.Equal(t, "info", InfoLevel.String())
  358. assert.Equal(t, "warning", WarnLevel.String())
  359. assert.Equal(t, "error", ErrorLevel.String())
  360. assert.Equal(t, "fatal", FatalLevel.String())
  361. assert.Equal(t, "panic", PanicLevel.String())
  362. }
  363. func TestParseLevel(t *testing.T) {
  364. l, err := ParseLevel("panic")
  365. assert.Nil(t, err)
  366. assert.Equal(t, PanicLevel, l)
  367. l, err = ParseLevel("PANIC")
  368. assert.Nil(t, err)
  369. assert.Equal(t, PanicLevel, l)
  370. l, err = ParseLevel("fatal")
  371. assert.Nil(t, err)
  372. assert.Equal(t, FatalLevel, l)
  373. l, err = ParseLevel("FATAL")
  374. assert.Nil(t, err)
  375. assert.Equal(t, FatalLevel, l)
  376. l, err = ParseLevel("error")
  377. assert.Nil(t, err)
  378. assert.Equal(t, ErrorLevel, l)
  379. l, err = ParseLevel("ERROR")
  380. assert.Nil(t, err)
  381. assert.Equal(t, ErrorLevel, l)
  382. l, err = ParseLevel("warn")
  383. assert.Nil(t, err)
  384. assert.Equal(t, WarnLevel, l)
  385. l, err = ParseLevel("WARN")
  386. assert.Nil(t, err)
  387. assert.Equal(t, WarnLevel, l)
  388. l, err = ParseLevel("warning")
  389. assert.Nil(t, err)
  390. assert.Equal(t, WarnLevel, l)
  391. l, err = ParseLevel("WARNING")
  392. assert.Nil(t, err)
  393. assert.Equal(t, WarnLevel, l)
  394. l, err = ParseLevel("info")
  395. assert.Nil(t, err)
  396. assert.Equal(t, InfoLevel, l)
  397. l, err = ParseLevel("INFO")
  398. assert.Nil(t, err)
  399. assert.Equal(t, InfoLevel, l)
  400. l, err = ParseLevel("debug")
  401. assert.Nil(t, err)
  402. assert.Equal(t, DebugLevel, l)
  403. l, err = ParseLevel("DEBUG")
  404. assert.Nil(t, err)
  405. assert.Equal(t, DebugLevel, l)
  406. l, err = ParseLevel("trace")
  407. assert.Nil(t, err)
  408. assert.Equal(t, TraceLevel, l)
  409. l, err = ParseLevel("TRACE")
  410. assert.Nil(t, err)
  411. assert.Equal(t, TraceLevel, l)
  412. l, err = ParseLevel("invalid")
  413. assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
  414. }
  415. func TestUnmarshalText(t *testing.T) {
  416. var u Level
  417. for _, level := range AllLevels {
  418. t.Run(level.String(), func(t *testing.T) {
  419. assert.NoError(t, u.UnmarshalText([]byte(level.String())))
  420. assert.Equal(t, level, u)
  421. })
  422. }
  423. t.Run("invalid", func(t *testing.T) {
  424. assert.Error(t, u.UnmarshalText([]byte("invalid")))
  425. })
  426. }
  427. func TestGetSetLevelRace(t *testing.T) {
  428. wg := sync.WaitGroup{}
  429. for i := 0; i < 100; i++ {
  430. wg.Add(1)
  431. go func(i int) {
  432. defer wg.Done()
  433. if i%2 == 0 {
  434. SetLevel(InfoLevel)
  435. } else {
  436. GetLevel()
  437. }
  438. }(i)
  439. }
  440. wg.Wait()
  441. }
  442. func TestLoggingRace(t *testing.T) {
  443. logger := New()
  444. var wg sync.WaitGroup
  445. wg.Add(100)
  446. for i := 0; i < 100; i++ {
  447. go func() {
  448. logger.Info("info")
  449. wg.Done()
  450. }()
  451. }
  452. wg.Wait()
  453. }
  454. func TestLoggingRaceWithHooksOnEntry(t *testing.T) {
  455. logger := New()
  456. hook := new(ModifyHook)
  457. logger.AddHook(hook)
  458. entry := logger.WithField("context", "clue")
  459. var wg sync.WaitGroup
  460. wg.Add(100)
  461. for i := 0; i < 100; i++ {
  462. go func() {
  463. entry.Info("info")
  464. wg.Done()
  465. }()
  466. }
  467. wg.Wait()
  468. }
  469. func TestReplaceHooks(t *testing.T) {
  470. old, cur := &TestHook{}, &TestHook{}
  471. logger := New()
  472. logger.SetOutput(ioutil.Discard)
  473. logger.AddHook(old)
  474. hooks := make(LevelHooks)
  475. hooks.Add(cur)
  476. replaced := logger.ReplaceHooks(hooks)
  477. logger.Info("test")
  478. assert.Equal(t, old.Fired, false)
  479. assert.Equal(t, cur.Fired, true)
  480. logger.ReplaceHooks(replaced)
  481. logger.Info("test")
  482. assert.Equal(t, old.Fired, true)
  483. }
  484. // Compile test
  485. func TestLogrusInterfaces(t *testing.T) {
  486. var buffer bytes.Buffer
  487. // This verifies FieldLogger and Ext1FieldLogger work as designed.
  488. // Please don't use them. Use Logger and Entry directly.
  489. fn := func(xl Ext1FieldLogger) {
  490. var l FieldLogger = xl
  491. b := l.WithField("key", "value")
  492. b.Debug("Test")
  493. }
  494. // test logger
  495. logger := New()
  496. logger.Out = &buffer
  497. fn(logger)
  498. // test Entry
  499. e := logger.WithField("another", "value")
  500. fn(e)
  501. }
  502. // Implements io.Writer using channels for synchronization, so we can wait on
  503. // the Entry.Writer goroutine to write in a non-racey way. This does assume that
  504. // there is a single call to Logger.Out for each message.
  505. type channelWriter chan []byte
  506. func (cw channelWriter) Write(p []byte) (int, error) {
  507. cw <- p
  508. return len(p), nil
  509. }
  510. func TestEntryWriter(t *testing.T) {
  511. cw := channelWriter(make(chan []byte, 1))
  512. log := New()
  513. log.Out = cw
  514. log.Formatter = new(JSONFormatter)
  515. log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n"))
  516. bs := <-cw
  517. var fields Fields
  518. err := json.Unmarshal(bs, &fields)
  519. assert.Nil(t, err)
  520. assert.Equal(t, fields["foo"], "bar")
  521. assert.Equal(t, fields["level"], "warning")
  522. }
  523. func TestLogLevelEnabled(t *testing.T) {
  524. log := New()
  525. log.SetLevel(PanicLevel)
  526. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  527. assert.Equal(t, false, log.IsLevelEnabled(FatalLevel))
  528. assert.Equal(t, false, log.IsLevelEnabled(ErrorLevel))
  529. assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))
  530. assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))
  531. assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))
  532. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  533. log.SetLevel(FatalLevel)
  534. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  535. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  536. assert.Equal(t, false, log.IsLevelEnabled(ErrorLevel))
  537. assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))
  538. assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))
  539. assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))
  540. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  541. log.SetLevel(ErrorLevel)
  542. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  543. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  544. assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))
  545. assert.Equal(t, false, log.IsLevelEnabled(WarnLevel))
  546. assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))
  547. assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))
  548. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  549. log.SetLevel(WarnLevel)
  550. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  551. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  552. assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))
  553. assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))
  554. assert.Equal(t, false, log.IsLevelEnabled(InfoLevel))
  555. assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))
  556. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  557. log.SetLevel(InfoLevel)
  558. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  559. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  560. assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))
  561. assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))
  562. assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))
  563. assert.Equal(t, false, log.IsLevelEnabled(DebugLevel))
  564. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  565. log.SetLevel(DebugLevel)
  566. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  567. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  568. assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))
  569. assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))
  570. assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))
  571. assert.Equal(t, true, log.IsLevelEnabled(DebugLevel))
  572. assert.Equal(t, false, log.IsLevelEnabled(TraceLevel))
  573. log.SetLevel(TraceLevel)
  574. assert.Equal(t, true, log.IsLevelEnabled(PanicLevel))
  575. assert.Equal(t, true, log.IsLevelEnabled(FatalLevel))
  576. assert.Equal(t, true, log.IsLevelEnabled(ErrorLevel))
  577. assert.Equal(t, true, log.IsLevelEnabled(WarnLevel))
  578. assert.Equal(t, true, log.IsLevelEnabled(InfoLevel))
  579. assert.Equal(t, true, log.IsLevelEnabled(DebugLevel))
  580. assert.Equal(t, true, log.IsLevelEnabled(TraceLevel))
  581. }
  582. func TestReportCallerOnTextFormatter(t *testing.T) {
  583. l := New()
  584. l.Formatter.(*TextFormatter).ForceColors = true
  585. l.Formatter.(*TextFormatter).DisableColors = false
  586. l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
  587. l.Formatter.(*TextFormatter).ForceColors = false
  588. l.Formatter.(*TextFormatter).DisableColors = true
  589. l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
  590. }