logger.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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"
  24. "os"
  25. "strings"
  26. "go.uber.org/zap/internal/bufferpool"
  27. "go.uber.org/zap/internal/stacktrace"
  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. addCaller bool
  41. onFatal zapcore.CheckWriteHook // default is WriteThenFatal
  42. name string
  43. errorOutput zapcore.WriteSyncer
  44. addStack zapcore.LevelEnabler
  45. callerSkip int
  46. clock zapcore.Clock
  47. }
  48. // New constructs a new Logger from the provided zapcore.Core and Options. If
  49. // the passed zapcore.Core is nil, it falls back to using a no-op
  50. // implementation.
  51. //
  52. // This is the most flexible way to construct a Logger, but also the most
  53. // verbose. For typical use cases, the highly-opinionated presets
  54. // (NewProduction, NewDevelopment, and NewExample) or the Config struct are
  55. // more convenient.
  56. //
  57. // For sample code, see the package-level AdvancedConfiguration example.
  58. func New(core zapcore.Core, options ...Option) *Logger {
  59. if core == nil {
  60. return NewNop()
  61. }
  62. log := &Logger{
  63. core: core,
  64. errorOutput: zapcore.Lock(os.Stderr),
  65. addStack: zapcore.FatalLevel + 1,
  66. clock: zapcore.DefaultClock,
  67. }
  68. return log.WithOptions(options...)
  69. }
  70. // NewNop returns a no-op Logger. It never writes out logs or internal errors,
  71. // and it never runs user-defined hooks.
  72. //
  73. // Using WithOptions to replace the Core or error output of a no-op Logger can
  74. // re-enable logging.
  75. func NewNop() *Logger {
  76. return &Logger{
  77. core: zapcore.NewNopCore(),
  78. errorOutput: zapcore.AddSync(io.Discard),
  79. addStack: zapcore.FatalLevel + 1,
  80. clock: zapcore.DefaultClock,
  81. }
  82. }
  83. // NewProduction builds a sensible production Logger that writes InfoLevel and
  84. // above logs to standard error as JSON.
  85. //
  86. // It's a shortcut for NewProductionConfig().Build(...Option).
  87. func NewProduction(options ...Option) (*Logger, error) {
  88. return NewProductionConfig().Build(options...)
  89. }
  90. // NewDevelopment builds a development Logger that writes DebugLevel and above
  91. // logs to standard error in a human-friendly format.
  92. //
  93. // It's a shortcut for NewDevelopmentConfig().Build(...Option).
  94. func NewDevelopment(options ...Option) (*Logger, error) {
  95. return NewDevelopmentConfig().Build(options...)
  96. }
  97. // Must is a helper that wraps a call to a function returning (*Logger, error)
  98. // and panics if the error is non-nil. It is intended for use in variable
  99. // initialization such as:
  100. //
  101. // var logger = zap.Must(zap.NewProduction())
  102. func Must(logger *Logger, err error) *Logger {
  103. if err != nil {
  104. panic(err)
  105. }
  106. return logger
  107. }
  108. // NewExample builds a Logger that's designed for use in zap's testable
  109. // examples. It writes DebugLevel and above logs to standard out as JSON, but
  110. // omits the timestamp and calling function to keep example output
  111. // short and deterministic.
  112. func NewExample(options ...Option) *Logger {
  113. encoderCfg := zapcore.EncoderConfig{
  114. MessageKey: "msg",
  115. LevelKey: "level",
  116. NameKey: "logger",
  117. EncodeLevel: zapcore.LowercaseLevelEncoder,
  118. EncodeTime: zapcore.ISO8601TimeEncoder,
  119. EncodeDuration: zapcore.StringDurationEncoder,
  120. }
  121. core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel)
  122. return New(core).WithOptions(options...)
  123. }
  124. // Sugar wraps the Logger to provide a more ergonomic, but slightly slower,
  125. // API. Sugaring a Logger is quite inexpensive, so it's reasonable for a
  126. // single application to use both Loggers and SugaredLoggers, converting
  127. // between them on the boundaries of performance-sensitive code.
  128. func (log *Logger) Sugar() *SugaredLogger {
  129. core := log.clone()
  130. core.callerSkip += 2
  131. return &SugaredLogger{core}
  132. }
  133. // Named adds a new path segment to the logger's name. Segments are joined by
  134. // periods. By default, Loggers are unnamed.
  135. func (log *Logger) Named(s string) *Logger {
  136. if s == "" {
  137. return log
  138. }
  139. l := log.clone()
  140. if log.name == "" {
  141. l.name = s
  142. } else {
  143. l.name = strings.Join([]string{l.name, s}, ".")
  144. }
  145. return l
  146. }
  147. // WithOptions clones the current Logger, applies the supplied Options, and
  148. // returns the resulting Logger. It's safe to use concurrently.
  149. func (log *Logger) WithOptions(opts ...Option) *Logger {
  150. c := log.clone()
  151. for _, opt := range opts {
  152. opt.apply(c)
  153. }
  154. return c
  155. }
  156. // With creates a child logger and adds structured context to it. Fields added
  157. // to the child don't affect the parent, and vice versa. Any fields that
  158. // require evaluation (such as Objects) are evaluated upon invocation of With.
  159. func (log *Logger) With(fields ...Field) *Logger {
  160. if len(fields) == 0 {
  161. return log
  162. }
  163. l := log.clone()
  164. l.core = l.core.With(fields)
  165. return l
  166. }
  167. // WithLazy creates a child logger and adds structured context to it lazily.
  168. //
  169. // The fields are evaluated only if the logger is further chained with [With]
  170. // or is written to with any of the log level methods.
  171. // Until that occurs, the logger may retain references to objects inside the fields,
  172. // and logging will reflect the state of an object at the time of logging,
  173. // not the time of WithLazy().
  174. //
  175. // WithLazy provides a worthwhile performance optimization for contextual loggers
  176. // when the likelihood of using the child logger is low,
  177. // such as error paths and rarely taken branches.
  178. //
  179. // Similar to [With], fields added to the child don't affect the parent, and vice versa.
  180. func (log *Logger) WithLazy(fields ...Field) *Logger {
  181. if len(fields) == 0 {
  182. return log
  183. }
  184. return log.WithOptions(WrapCore(func(core zapcore.Core) zapcore.Core {
  185. return zapcore.NewLazyWith(core, fields)
  186. }))
  187. }
  188. // Level reports the minimum enabled level for this logger.
  189. //
  190. // For NopLoggers, this is [zapcore.InvalidLevel].
  191. func (log *Logger) Level() zapcore.Level {
  192. return zapcore.LevelOf(log.core)
  193. }
  194. // Check returns a CheckedEntry if logging a message at the specified level
  195. // is enabled. It's a completely optional optimization; in high-performance
  196. // applications, Check can help avoid allocating a slice to hold fields.
  197. func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
  198. return log.check(lvl, msg)
  199. }
  200. // Log logs a message at the specified level. The message includes any fields
  201. // passed at the log site, as well as any fields accumulated on the logger.
  202. // Any Fields that require evaluation (such as Objects) are evaluated upon
  203. // invocation of Log.
  204. func (log *Logger) Log(lvl zapcore.Level, msg string, fields ...Field) {
  205. if ce := log.check(lvl, msg); ce != nil {
  206. ce.Write(fields...)
  207. }
  208. }
  209. // Debug logs a message at DebugLevel. The message includes any fields passed
  210. // at the log site, as well as any fields accumulated on the logger.
  211. func (log *Logger) Debug(msg string, fields ...Field) {
  212. if ce := log.check(DebugLevel, msg); ce != nil {
  213. ce.Write(fields...)
  214. }
  215. }
  216. // Info logs a message at InfoLevel. The message includes any fields passed
  217. // at the log site, as well as any fields accumulated on the logger.
  218. func (log *Logger) Info(msg string, fields ...Field) {
  219. if ce := log.check(InfoLevel, msg); ce != nil {
  220. ce.Write(fields...)
  221. }
  222. }
  223. // Warn logs a message at WarnLevel. The message includes any fields passed
  224. // at the log site, as well as any fields accumulated on the logger.
  225. func (log *Logger) Warn(msg string, fields ...Field) {
  226. if ce := log.check(WarnLevel, msg); ce != nil {
  227. ce.Write(fields...)
  228. }
  229. }
  230. // Error logs a message at ErrorLevel. The message includes any fields passed
  231. // at the log site, as well as any fields accumulated on the logger.
  232. func (log *Logger) Error(msg string, fields ...Field) {
  233. if ce := log.check(ErrorLevel, msg); ce != nil {
  234. ce.Write(fields...)
  235. }
  236. }
  237. // DPanic logs a message at DPanicLevel. The message includes any fields
  238. // passed at the log site, as well as any fields accumulated on the logger.
  239. //
  240. // If the logger is in development mode, it then panics (DPanic means
  241. // "development panic"). This is useful for catching errors that are
  242. // recoverable, but shouldn't ever happen.
  243. func (log *Logger) DPanic(msg string, fields ...Field) {
  244. if ce := log.check(DPanicLevel, msg); ce != nil {
  245. ce.Write(fields...)
  246. }
  247. }
  248. // Panic logs a message at PanicLevel. The message includes any fields passed
  249. // at the log site, as well as any fields accumulated on the logger.
  250. //
  251. // The logger then panics, even if logging at PanicLevel is disabled.
  252. func (log *Logger) Panic(msg string, fields ...Field) {
  253. if ce := log.check(PanicLevel, msg); ce != nil {
  254. ce.Write(fields...)
  255. }
  256. }
  257. // Fatal logs a message at FatalLevel. The message includes any fields passed
  258. // at the log site, as well as any fields accumulated on the logger.
  259. //
  260. // The logger then calls os.Exit(1), even if logging at FatalLevel is
  261. // disabled.
  262. func (log *Logger) Fatal(msg string, fields ...Field) {
  263. if ce := log.check(FatalLevel, msg); ce != nil {
  264. ce.Write(fields...)
  265. }
  266. }
  267. // Sync calls the underlying Core's Sync method, flushing any buffered log
  268. // entries. Applications should take care to call Sync before exiting.
  269. func (log *Logger) Sync() error {
  270. return log.core.Sync()
  271. }
  272. // Core returns the Logger's underlying zapcore.Core.
  273. func (log *Logger) Core() zapcore.Core {
  274. return log.core
  275. }
  276. // Name returns the Logger's underlying name,
  277. // or an empty string if the logger is unnamed.
  278. func (log *Logger) Name() string {
  279. return log.name
  280. }
  281. func (log *Logger) clone() *Logger {
  282. clone := *log
  283. return &clone
  284. }
  285. func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
  286. // Logger.check must always be called directly by a method in the
  287. // Logger interface (e.g., Check, Info, Fatal).
  288. // This skips Logger.check and the Info/Fatal/Check/etc. method that
  289. // called it.
  290. const callerSkipOffset = 2
  291. // Check the level first to reduce the cost of disabled log calls.
  292. // Since Panic and higher may exit, we skip the optimization for those levels.
  293. if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) {
  294. return nil
  295. }
  296. // Create basic checked entry thru the core; this will be non-nil if the
  297. // log message will actually be written somewhere.
  298. ent := zapcore.Entry{
  299. LoggerName: log.name,
  300. Time: log.clock.Now(),
  301. Level: lvl,
  302. Message: msg,
  303. }
  304. ce := log.core.Check(ent, nil)
  305. willWrite := ce != nil
  306. // Set up any required terminal behavior.
  307. switch ent.Level {
  308. case zapcore.PanicLevel:
  309. ce = ce.After(ent, zapcore.WriteThenPanic)
  310. case zapcore.FatalLevel:
  311. onFatal := log.onFatal
  312. // nil or WriteThenNoop will lead to continued execution after
  313. // a Fatal log entry, which is unexpected. For example,
  314. //
  315. // f, err := os.Open(..)
  316. // if err != nil {
  317. // log.Fatal("cannot open", zap.Error(err))
  318. // }
  319. // fmt.Println(f.Name())
  320. //
  321. // The f.Name() will panic if we continue execution after the
  322. // log.Fatal.
  323. if onFatal == nil || onFatal == zapcore.WriteThenNoop {
  324. onFatal = zapcore.WriteThenFatal
  325. }
  326. ce = ce.After(ent, onFatal)
  327. case zapcore.DPanicLevel:
  328. if log.development {
  329. ce = ce.After(ent, zapcore.WriteThenPanic)
  330. }
  331. }
  332. // Only do further annotation if we're going to write this message; checked
  333. // entries that exist only for terminal behavior don't benefit from
  334. // annotation.
  335. if !willWrite {
  336. return ce
  337. }
  338. // Thread the error output through to the CheckedEntry.
  339. ce.ErrorOutput = log.errorOutput
  340. addStack := log.addStack.Enabled(ce.Level)
  341. if !log.addCaller && !addStack {
  342. return ce
  343. }
  344. // Adding the caller or stack trace requires capturing the callers of
  345. // this function. We'll share information between these two.
  346. stackDepth := stacktrace.First
  347. if addStack {
  348. stackDepth = stacktrace.Full
  349. }
  350. stack := stacktrace.Capture(log.callerSkip+callerSkipOffset, stackDepth)
  351. defer stack.Free()
  352. if stack.Count() == 0 {
  353. if log.addCaller {
  354. fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC())
  355. _ = log.errorOutput.Sync()
  356. }
  357. return ce
  358. }
  359. frame, more := stack.Next()
  360. if log.addCaller {
  361. ce.Caller = zapcore.EntryCaller{
  362. Defined: frame.PC != 0,
  363. PC: frame.PC,
  364. File: frame.File,
  365. Line: frame.Line,
  366. Function: frame.Function,
  367. }
  368. }
  369. if addStack {
  370. buffer := bufferpool.Get()
  371. defer buffer.Free()
  372. stackfmt := stacktrace.NewFormatter(buffer)
  373. // We've already extracted the first frame, so format that
  374. // separately and defer to stackfmt for the rest.
  375. stackfmt.FormatFrame(frame)
  376. if more {
  377. stackfmt.FormatStack(stack)
  378. }
  379. ce.Stack = buffer.String()
  380. }
  381. return ce
  382. }