global.go 5.2 KB

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