global.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 = 2
  31. _loggerWriterDepth = 2
  32. )
  33. var (
  34. _globalMu sync.RWMutex
  35. _globalL = NewNop()
  36. _globalS = _globalL.Sugar()
  37. )
  38. // L returns the global Logger, which can be reconfigured with ReplaceGlobals.
  39. // It's safe for concurrent use.
  40. func L() *Logger {
  41. _globalMu.RLock()
  42. l := _globalL
  43. _globalMu.RUnlock()
  44. return l
  45. }
  46. // S returns the global SugaredLogger, which can be reconfigured with
  47. // ReplaceGlobals. It's safe for concurrent use.
  48. func S() *SugaredLogger {
  49. _globalMu.RLock()
  50. s := _globalS
  51. _globalMu.RUnlock()
  52. return s
  53. }
  54. // ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a
  55. // function to restore the original values. It's safe for concurrent use.
  56. func ReplaceGlobals(logger *Logger) func() {
  57. _globalMu.Lock()
  58. prev := _globalL
  59. _globalL = logger
  60. _globalS = logger.Sugar()
  61. _globalMu.Unlock()
  62. return func() { ReplaceGlobals(prev) }
  63. }
  64. // NewStdLog returns a *log.Logger which writes to the supplied zap Logger at
  65. // InfoLevel. To redirect the standard library's package-global logging
  66. // functions, use RedirectStdLog instead.
  67. func NewStdLog(l *Logger) *log.Logger {
  68. logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth))
  69. f := logger.Info
  70. return log.New(&loggerWriter{f}, "" /* prefix */, 0 /* flags */)
  71. }
  72. // NewStdLogAt returns *log.Logger which writes to supplied zap logger at
  73. // required level.
  74. func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error) {
  75. logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth))
  76. var logFunc func(string, ...zapcore.Field)
  77. switch level {
  78. case DebugLevel:
  79. logFunc = logger.Debug
  80. case InfoLevel:
  81. logFunc = logger.Info
  82. case WarnLevel:
  83. logFunc = logger.Warn
  84. case ErrorLevel:
  85. logFunc = logger.Error
  86. case DPanicLevel:
  87. logFunc = logger.DPanic
  88. case PanicLevel:
  89. logFunc = logger.Panic
  90. case FatalLevel:
  91. logFunc = logger.Fatal
  92. default:
  93. return nil, fmt.Errorf("unrecognized level: %q", level)
  94. }
  95. return log.New(&loggerWriter{logFunc}, "" /* prefix */, 0 /* flags */), nil
  96. }
  97. // RedirectStdLog redirects output from the standard library's package-global
  98. // logger to the supplied logger at InfoLevel. Since zap already handles caller
  99. // annotations, timestamps, etc., it automatically disables the standard
  100. // library's annotations and prefixing.
  101. //
  102. // It returns a function to restore the original prefix and flags and reset the
  103. // standard library's output to os.Stdout.
  104. func RedirectStdLog(l *Logger) func() {
  105. flags := log.Flags()
  106. prefix := log.Prefix()
  107. log.SetFlags(0)
  108. log.SetPrefix("")
  109. logFunc := l.WithOptions(
  110. AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth),
  111. ).Info
  112. log.SetOutput(&loggerWriter{logFunc})
  113. return func() {
  114. log.SetFlags(flags)
  115. log.SetPrefix(prefix)
  116. log.SetOutput(os.Stderr)
  117. }
  118. }
  119. type loggerWriter struct {
  120. logFunc func(msg string, fields ...zapcore.Field)
  121. }
  122. func (l *loggerWriter) Write(p []byte) (int, error) {
  123. p = bytes.TrimSpace(p)
  124. l.logFunc(string(p))
  125. return len(p), nil
  126. }