logger.go 12 KB

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