global.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. "bytes"
  23. "fmt"
  24. "log"
  25. "os"
  26. "sync"
  27. "go.uber.org/zap/zapcore"
  28. )
  29. const (
  30. _stdLogDefaultDepth = 1
  31. _loggerWriterDepth = 2
  32. _programmerErrorTemplate = "You've found a bug in zap! Please file a bug at " +
  33. "https://github.com/uber-go/zap/issues/new and reference this error: %v"
  34. )
  35. var (
  36. _globalMu sync.RWMutex
  37. _globalL = NewNop()
  38. _globalS = _globalL.Sugar()
  39. )
  40. // L returns the global Logger, which can be reconfigured with ReplaceGlobals.
  41. // It's safe for concurrent use.
  42. func L() *Logger {
  43. _globalMu.RLock()
  44. l := _globalL
  45. _globalMu.RUnlock()
  46. return l
  47. }
  48. // S returns the global SugaredLogger, which can be reconfigured with
  49. // ReplaceGlobals. It's safe for concurrent use.
  50. func S() *SugaredLogger {
  51. _globalMu.RLock()
  52. s := _globalS
  53. _globalMu.RUnlock()
  54. return s
  55. }
  56. // ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a
  57. // function to restore the original values. It's safe for concurrent use.
  58. func ReplaceGlobals(logger *Logger) func() {
  59. _globalMu.Lock()
  60. prev := _globalL
  61. _globalL = logger
  62. _globalS = logger.Sugar()
  63. _globalMu.Unlock()
  64. return func() { ReplaceGlobals(prev) }
  65. }
  66. // NewStdLog returns a *log.Logger which writes to the supplied zap Logger at
  67. // InfoLevel. To redirect the standard library's package-global logging
  68. // functions, use RedirectStdLog instead.
  69. func NewStdLog(l *Logger) *log.Logger {
  70. logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth))
  71. f := logger.Info
  72. return log.New(&loggerWriter{f}, "" /* prefix */, 0 /* flags */)
  73. }
  74. // NewStdLogAt returns *log.Logger which writes to supplied zap logger at
  75. // required level.
  76. func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error) {
  77. logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth))
  78. logFunc, err := levelToFunc(logger, level)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return log.New(&loggerWriter{logFunc}, "" /* prefix */, 0 /* flags */), nil
  83. }
  84. // RedirectStdLog redirects output from the standard library's package-global
  85. // logger to the supplied logger at InfoLevel. Since zap already handles caller
  86. // annotations, timestamps, etc., it automatically disables the standard
  87. // library's annotations and prefixing.
  88. //
  89. // It returns a function to restore the original prefix and flags and reset the
  90. // standard library's output to os.Stderr.
  91. func RedirectStdLog(l *Logger) func() {
  92. f, err := redirectStdLogAt(l, InfoLevel)
  93. if err != nil {
  94. // Can't get here, since passing InfoLevel to redirectStdLogAt always
  95. // works.
  96. panic(fmt.Sprintf(_programmerErrorTemplate, err))
  97. }
  98. return f
  99. }
  100. // RedirectStdLogAt redirects output from the standard library's package-global
  101. // logger to the supplied logger at the specified level. Since zap already
  102. // handles caller annotations, timestamps, etc., it automatically disables the
  103. // standard library's annotations and prefixing.
  104. //
  105. // It returns a function to restore the original prefix and flags and reset the
  106. // standard library's output to os.Stderr.
  107. func RedirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) {
  108. return redirectStdLogAt(l, level)
  109. }
  110. func redirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) {
  111. flags := log.Flags()
  112. prefix := log.Prefix()
  113. log.SetFlags(0)
  114. log.SetPrefix("")
  115. logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth))
  116. logFunc, err := levelToFunc(logger, level)
  117. if err != nil {
  118. return nil, err
  119. }
  120. log.SetOutput(&loggerWriter{logFunc})
  121. return func() {
  122. log.SetFlags(flags)
  123. log.SetPrefix(prefix)
  124. log.SetOutput(os.Stderr)
  125. }, nil
  126. }
  127. func levelToFunc(logger *Logger, lvl zapcore.Level) (func(string, ...Field), error) {
  128. switch lvl {
  129. case DebugLevel:
  130. return logger.Debug, nil
  131. case InfoLevel:
  132. return logger.Info, nil
  133. case WarnLevel:
  134. return logger.Warn, nil
  135. case ErrorLevel:
  136. return logger.Error, nil
  137. case DPanicLevel:
  138. return logger.DPanic, nil
  139. case PanicLevel:
  140. return logger.Panic, nil
  141. case FatalLevel:
  142. return logger.Fatal, nil
  143. }
  144. return nil, fmt.Errorf("unrecognized level: %q", lvl)
  145. }
  146. type loggerWriter struct {
  147. logFunc func(msg string, fields ...Field)
  148. }
  149. func (l *loggerWriter) Write(p []byte) (int, error) {
  150. p = bytes.TrimSpace(p)
  151. l.logFunc(string(p))
  152. return len(p), nil
  153. }