logger.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright (c) 2017 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 zaptest
  21. import (
  22. "bytes"
  23. "go.uber.org/zap"
  24. "go.uber.org/zap/zapcore"
  25. )
  26. // LoggerOption configures the test logger built by NewLogger.
  27. type LoggerOption interface {
  28. applyLoggerOption(*loggerOptions)
  29. }
  30. type loggerOptions struct {
  31. Level zapcore.LevelEnabler
  32. zapOptions []zap.Option
  33. }
  34. type loggerOptionFunc func(*loggerOptions)
  35. func (f loggerOptionFunc) applyLoggerOption(opts *loggerOptions) {
  36. f(opts)
  37. }
  38. // Level controls which messages are logged by a test Logger built by
  39. // NewLogger.
  40. func Level(enab zapcore.LevelEnabler) LoggerOption {
  41. return loggerOptionFunc(func(opts *loggerOptions) {
  42. opts.Level = enab
  43. })
  44. }
  45. // WrapOptions adds zap.Option's to a test Logger built by NewLogger.
  46. func WrapOptions(zapOpts ...zap.Option) LoggerOption {
  47. return loggerOptionFunc(func(opts *loggerOptions) {
  48. opts.zapOptions = zapOpts
  49. })
  50. }
  51. // NewLogger builds a new Logger that logs all messages to the given
  52. // testing.TB.
  53. //
  54. // logger := zaptest.NewLogger(t)
  55. //
  56. // Use this with a *testing.T or *testing.B to get logs which get printed only
  57. // if a test fails or if you ran go test -v.
  58. //
  59. // The returned logger defaults to logging debug level messages and above.
  60. // This may be changed by passing a zaptest.Level during construction.
  61. //
  62. // logger := zaptest.NewLogger(t, zaptest.Level(zap.WarnLevel))
  63. //
  64. // You may also pass zap.Option's to customize test logger.
  65. //
  66. // logger := zaptest.NewLogger(t, zaptest.WrapOptions(zap.AddCaller()))
  67. func NewLogger(t TestingT, opts ...LoggerOption) *zap.Logger {
  68. cfg := loggerOptions{
  69. Level: zapcore.DebugLevel,
  70. }
  71. for _, o := range opts {
  72. o.applyLoggerOption(&cfg)
  73. }
  74. writer := newTestingWriter(t)
  75. zapOptions := []zap.Option{
  76. // Send zap errors to the same writer and mark the test as failed if
  77. // that happens.
  78. zap.ErrorOutput(writer.WithMarkFailed(true)),
  79. }
  80. zapOptions = append(zapOptions, cfg.zapOptions...)
  81. return zap.New(
  82. zapcore.NewCore(
  83. zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()),
  84. writer,
  85. cfg.Level,
  86. ),
  87. zapOptions...,
  88. )
  89. }
  90. // testingWriter is a WriteSyncer that writes to the given testing.TB.
  91. type testingWriter struct {
  92. t TestingT
  93. // If true, the test will be marked as failed if this testingWriter is
  94. // ever used.
  95. markFailed bool
  96. }
  97. func newTestingWriter(t TestingT) testingWriter {
  98. return testingWriter{t: t}
  99. }
  100. // WithMarkFailed returns a copy of this testingWriter with markFailed set to
  101. // the provided value.
  102. func (w testingWriter) WithMarkFailed(v bool) testingWriter {
  103. w.markFailed = v
  104. return w
  105. }
  106. func (w testingWriter) Write(p []byte) (n int, err error) {
  107. n = len(p)
  108. // Strip trailing newline because t.Log always adds one.
  109. p = bytes.TrimRight(p, "\n")
  110. // Note: t.Log is safe for concurrent use.
  111. w.t.Logf("%s", p)
  112. if w.markFailed {
  113. w.t.Fail()
  114. }
  115. return n, nil
  116. }
  117. func (w testingWriter) Sync() error {
  118. return nil
  119. }