logger.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "fmt"
  23. "io/ioutil"
  24. "os"
  25. "runtime"
  26. "strings"
  27. "time"
  28. "go.uber.org/zap/zapcore"
  29. )
  30. // A Logger provides fast, leveled, structured logging. All methods are safe
  31. // for concurrent use.
  32. //
  33. // The Logger is designed for contexts in which every microsecond and every
  34. // allocation matters, so its API intentionally favors performance and type
  35. // safety over brevity. For most applications, the SugaredLogger strikes a
  36. // better balance between performance and ergonomics.
  37. type Logger struct {
  38. core zapcore.Core
  39. development bool
  40. name string
  41. errorOutput zapcore.WriteSyncer
  42. addCaller bool
  43. addStack zapcore.LevelEnabler
  44. callerSkip int
  45. }
  46. // New constructs a new Logger from the provided zapcore.Core and Options. If
  47. // the passed zapcore.Core is nil, it falls back to using a no-op
  48. // implementation.
  49. //
  50. // This is the most flexible way to construct a Logger, but also the most
  51. // verbose. For typical use cases, the highly-opinionated presets
  52. // (NewProduction, NewDevelopment, and NewExample) or the Config struct are
  53. // more convenient.
  54. //
  55. // For sample code, see the package-level AdvancedConfiguration example.
  56. func New(core zapcore.Core, options ...Option) *Logger {
  57. if core == nil {
  58. return NewNop()
  59. }
  60. log := &Logger{
  61. core: core,
  62. errorOutput: zapcore.Lock(os.Stderr),
  63. addStack: zapcore.FatalLevel + 1,
  64. }
  65. return log.WithOptions(options...)
  66. }
  67. // NewNop returns a no-op Logger. It never writes out logs or internal errors,
  68. // and it never runs user-defined hooks.
  69. //
  70. // Using WithOptions to replace the Core or error output of a no-op Logger can
  71. // re-enable logging.
  72. func NewNop() *Logger {
  73. return &Logger{
  74. core: zapcore.NewNopCore(),
  75. errorOutput: zapcore.AddSync(ioutil.Discard),
  76. addStack: zapcore.FatalLevel + 1,
  77. }
  78. }
  79. // NewProduction builds a sensible production Logger that writes InfoLevel and
  80. // above logs to standard error as JSON.
  81. //
  82. // It's a shortcut for NewProductionConfig().Build(...Option).
  83. func NewProduction(options ...Option) (*Logger, error) {
  84. return NewProductionConfig().Build(options...)
  85. }
  86. // NewDevelopment builds a development Logger that writes DebugLevel and above
  87. // logs to standard error in a human-friendly format.
  88. //
  89. // It's a shortcut for NewDevelopmentConfig().Build(...Option).
  90. func NewDevelopment(options ...Option) (*Logger, error) {
  91. return NewDevelopmentConfig().Build(options...)
  92. }
  93. // NewExample builds a Logger that's designed for use in zap's testable
  94. // examples. It writes DebugLevel and above logs to standard out as JSON, but
  95. // omits the timestamp and calling function to keep example output
  96. // short and deterministic.
  97. func NewExample(options ...Option) *Logger {
  98. encoderCfg := zapcore.EncoderConfig{
  99. MessageKey: "msg",
  100. LevelKey: "level",
  101. NameKey: "logger",
  102. EncodeLevel: zapcore.LowercaseLevelEncoder,
  103. EncodeTime: zapcore.ISO8601TimeEncoder,
  104. EncodeDuration: zapcore.StringDurationEncoder,
  105. }
  106. core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel)
  107. return New(core).WithOptions(options...)
  108. }
  109. // Sugar wraps the Logger to provide a more ergonomic, but slightly slower,
  110. // API. Sugaring a Logger is quite inexpensive, so it's reasonable for a
  111. // single application to use both Loggers and SugaredLoggers, converting
  112. // between them on the boundaries of performance-sensitive code.
  113. func (log *Logger) Sugar() *SugaredLogger {
  114. core := log.clone()
  115. core.callerSkip += 2
  116. return &SugaredLogger{core}
  117. }
  118. // Named adds a new path segment to the logger's name. Segments are joined by
  119. // periods. By default, Loggers are unnamed.
  120. func (log *Logger) Named(s string) *Logger {
  121. if s == "" {
  122. return log
  123. }
  124. l := log.clone()
  125. if log.name == "" {
  126. l.name = s
  127. } else {
  128. l.name = strings.Join([]string{l.name, s}, ".")
  129. }
  130. return l
  131. }
  132. // WithOptions clones the current Logger, applies the supplied Options, and
  133. // returns the resulting Logger. It's safe to use concurrently.
  134. func (log *Logger) WithOptions(opts ...Option) *Logger {
  135. c := log.clone()
  136. for _, opt := range opts {
  137. opt.apply(c)
  138. }
  139. return c
  140. }
  141. // With creates a child logger and adds structured context to it. Fields added
  142. // to the child don't affect the parent, and vice versa.
  143. func (log *Logger) With(fields ...Field) *Logger {
  144. if len(fields) == 0 {
  145. return log
  146. }
  147. l := log.clone()
  148. l.core = l.core.With(fields)
  149. return l
  150. }
  151. // Check returns a CheckedEntry if logging a message at the specified level
  152. // is enabled. It's a completely optional optimization; in high-performance
  153. // applications, Check can help avoid allocating a slice to hold fields.
  154. func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
  155. return log.check(lvl, msg)
  156. }
  157. // Debug logs a message at DebugLevel. The message includes any fields passed
  158. // at the log site, as well as any fields accumulated on the logger.
  159. func (log *Logger) Debug(msg string, fields ...Field) {
  160. if ce := log.check(DebugLevel, msg); ce != nil {
  161. ce.Write(fields...)
  162. }
  163. }
  164. // Info logs a message at InfoLevel. The message includes any fields passed
  165. // at the log site, as well as any fields accumulated on the logger.
  166. func (log *Logger) Info(msg string, fields ...Field) {
  167. if ce := log.check(InfoLevel, msg); ce != nil {
  168. ce.Write(fields...)
  169. }
  170. }
  171. // Warn logs a message at WarnLevel. The message includes any fields passed
  172. // at the log site, as well as any fields accumulated on the logger.
  173. func (log *Logger) Warn(msg string, fields ...Field) {
  174. if ce := log.check(WarnLevel, msg); ce != nil {
  175. ce.Write(fields...)
  176. }
  177. }
  178. // Error logs a message at ErrorLevel. The message includes any fields passed
  179. // at the log site, as well as any fields accumulated on the logger.
  180. func (log *Logger) Error(msg string, fields ...Field) {
  181. if ce := log.check(ErrorLevel, msg); ce != nil {
  182. ce.Write(fields...)
  183. }
  184. }
  185. // DPanic logs a message at DPanicLevel. The message includes any fields
  186. // passed at the log site, as well as any fields accumulated on the logger.
  187. //
  188. // If the logger is in development mode, it then panics (DPanic means
  189. // "development panic"). This is useful for catching errors that are
  190. // recoverable, but shouldn't ever happen.
  191. func (log *Logger) DPanic(msg string, fields ...Field) {
  192. if ce := log.check(DPanicLevel, msg); ce != nil {
  193. ce.Write(fields...)
  194. }
  195. }
  196. // Panic logs a message at PanicLevel. The message includes any fields passed
  197. // at the log site, as well as any fields accumulated on the logger.
  198. //
  199. // The logger then panics, even if logging at PanicLevel is disabled.
  200. func (log *Logger) Panic(msg string, fields ...Field) {
  201. if ce := log.check(PanicLevel, msg); ce != nil {
  202. ce.Write(fields...)
  203. }
  204. }
  205. // Fatal logs a message at FatalLevel. The message includes any fields passed
  206. // at the log site, as well as any fields accumulated on the logger.
  207. //
  208. // The logger then calls os.Exit(1), even if logging at FatalLevel is
  209. // disabled.
  210. func (log *Logger) Fatal(msg string, fields ...Field) {
  211. if ce := log.check(FatalLevel, msg); ce != nil {
  212. ce.Write(fields...)
  213. }
  214. }
  215. // Sync calls the underlying Core's Sync method, flushing any buffered log
  216. // entries. Applications should take care to call Sync before exiting.
  217. func (log *Logger) Sync() error {
  218. return log.core.Sync()
  219. }
  220. // Core returns the Logger's underlying zapcore.Core.
  221. func (log *Logger) Core() zapcore.Core {
  222. return log.core
  223. }
  224. func (log *Logger) clone() *Logger {
  225. copy := *log
  226. return &copy
  227. }
  228. func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
  229. // check must always be called directly by a method in the Logger interface
  230. // (e.g., Check, Info, Fatal).
  231. const callerSkipOffset = 2
  232. // Create basic checked entry thru the core; this will be non-nil if the
  233. // log message will actually be written somewhere.
  234. ent := zapcore.Entry{
  235. LoggerName: log.name,
  236. Time: time.Now(),
  237. Level: lvl,
  238. Message: msg,
  239. }
  240. ce := log.core.Check(ent, nil)
  241. willWrite := ce != nil
  242. // Set up any required terminal behavior.
  243. switch ent.Level {
  244. case zapcore.PanicLevel:
  245. ce = ce.Should(ent, zapcore.WriteThenPanic)
  246. case zapcore.FatalLevel:
  247. ce = ce.Should(ent, zapcore.WriteThenFatal)
  248. case zapcore.DPanicLevel:
  249. if log.development {
  250. ce = ce.Should(ent, zapcore.WriteThenPanic)
  251. }
  252. }
  253. // Only do further annotation if we're going to write this message; checked
  254. // entries that exist only for terminal behavior don't benefit from
  255. // annotation.
  256. if !willWrite {
  257. return ce
  258. }
  259. // Thread the error output through to the CheckedEntry.
  260. ce.ErrorOutput = log.errorOutput
  261. if log.addCaller {
  262. ce.Entry.Caller = zapcore.NewEntryCaller(runtime.Caller(log.callerSkip + callerSkipOffset))
  263. if !ce.Entry.Caller.Defined {
  264. fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", time.Now().UTC())
  265. log.errorOutput.Sync()
  266. }
  267. }
  268. if log.addStack.Enabled(ce.Entry.Level) {
  269. ce.Entry.Stack = Stack("").String
  270. }
  271. return ce
  272. }