blob: f116bd936fe2d195370f0634319f5ade9b089a1b [file] [log] [blame]
Don Newton7577f072020-01-06 12:41:11 -05001// 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
21package zap
22
23import (
24 "fmt"
25 "io/ioutil"
26 "os"
27 "runtime"
28 "strings"
Don Newton7577f072020-01-06 12:41:11 -050029
30 "go.uber.org/zap/zapcore"
31)
32
33// A Logger provides fast, leveled, structured logging. All methods are safe
34// for concurrent use.
35//
36// The Logger is designed for contexts in which every microsecond and every
37// allocation matters, so its API intentionally favors performance and type
38// safety over brevity. For most applications, the SugaredLogger strikes a
39// better balance between performance and ergonomics.
40type Logger struct {
41 core zapcore.Core
42
43 development bool
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000044 addCaller bool
45 onFatal zapcore.CheckWriteAction // default is WriteThenFatal
46
Don Newton7577f072020-01-06 12:41:11 -050047 name string
48 errorOutput zapcore.WriteSyncer
49
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000050 addStack zapcore.LevelEnabler
Don Newton7577f072020-01-06 12:41:11 -050051
52 callerSkip int
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000053
54 clock zapcore.Clock
Don Newton7577f072020-01-06 12:41:11 -050055}
56
57// New constructs a new Logger from the provided zapcore.Core and Options. If
58// the passed zapcore.Core is nil, it falls back to using a no-op
59// implementation.
60//
61// This is the most flexible way to construct a Logger, but also the most
62// verbose. For typical use cases, the highly-opinionated presets
63// (NewProduction, NewDevelopment, and NewExample) or the Config struct are
64// more convenient.
65//
66// For sample code, see the package-level AdvancedConfiguration example.
67func New(core zapcore.Core, options ...Option) *Logger {
68 if core == nil {
69 return NewNop()
70 }
71 log := &Logger{
72 core: core,
73 errorOutput: zapcore.Lock(os.Stderr),
74 addStack: zapcore.FatalLevel + 1,
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000075 clock: zapcore.DefaultClock,
Don Newton7577f072020-01-06 12:41:11 -050076 }
77 return log.WithOptions(options...)
78}
79
80// NewNop returns a no-op Logger. It never writes out logs or internal errors,
81// and it never runs user-defined hooks.
82//
83// Using WithOptions to replace the Core or error output of a no-op Logger can
84// re-enable logging.
85func NewNop() *Logger {
86 return &Logger{
87 core: zapcore.NewNopCore(),
88 errorOutput: zapcore.AddSync(ioutil.Discard),
89 addStack: zapcore.FatalLevel + 1,
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000090 clock: zapcore.DefaultClock,
Don Newton7577f072020-01-06 12:41:11 -050091 }
92}
93
94// NewProduction builds a sensible production Logger that writes InfoLevel and
95// above logs to standard error as JSON.
96//
97// It's a shortcut for NewProductionConfig().Build(...Option).
98func NewProduction(options ...Option) (*Logger, error) {
99 return NewProductionConfig().Build(options...)
100}
101
102// NewDevelopment builds a development Logger that writes DebugLevel and above
103// logs to standard error in a human-friendly format.
104//
105// It's a shortcut for NewDevelopmentConfig().Build(...Option).
106func NewDevelopment(options ...Option) (*Logger, error) {
107 return NewDevelopmentConfig().Build(options...)
108}
109
110// NewExample builds a Logger that's designed for use in zap's testable
111// examples. It writes DebugLevel and above logs to standard out as JSON, but
112// omits the timestamp and calling function to keep example output
113// short and deterministic.
114func NewExample(options ...Option) *Logger {
115 encoderCfg := zapcore.EncoderConfig{
116 MessageKey: "msg",
117 LevelKey: "level",
118 NameKey: "logger",
119 EncodeLevel: zapcore.LowercaseLevelEncoder,
120 EncodeTime: zapcore.ISO8601TimeEncoder,
121 EncodeDuration: zapcore.StringDurationEncoder,
122 }
123 core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel)
124 return New(core).WithOptions(options...)
125}
126
127// Sugar wraps the Logger to provide a more ergonomic, but slightly slower,
128// API. Sugaring a Logger is quite inexpensive, so it's reasonable for a
129// single application to use both Loggers and SugaredLoggers, converting
130// between them on the boundaries of performance-sensitive code.
131func (log *Logger) Sugar() *SugaredLogger {
132 core := log.clone()
133 core.callerSkip += 2
134 return &SugaredLogger{core}
135}
136
137// Named adds a new path segment to the logger's name. Segments are joined by
138// periods. By default, Loggers are unnamed.
139func (log *Logger) Named(s string) *Logger {
140 if s == "" {
141 return log
142 }
143 l := log.clone()
144 if log.name == "" {
145 l.name = s
146 } else {
147 l.name = strings.Join([]string{l.name, s}, ".")
148 }
149 return l
150}
151
152// WithOptions clones the current Logger, applies the supplied Options, and
153// returns the resulting Logger. It's safe to use concurrently.
154func (log *Logger) WithOptions(opts ...Option) *Logger {
155 c := log.clone()
156 for _, opt := range opts {
157 opt.apply(c)
158 }
159 return c
160}
161
162// With creates a child logger and adds structured context to it. Fields added
163// to the child don't affect the parent, and vice versa.
164func (log *Logger) With(fields ...Field) *Logger {
165 if len(fields) == 0 {
166 return log
167 }
168 l := log.clone()
169 l.core = l.core.With(fields)
170 return l
171}
172
173// Check returns a CheckedEntry if logging a message at the specified level
174// is enabled. It's a completely optional optimization; in high-performance
175// applications, Check can help avoid allocating a slice to hold fields.
176func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
177 return log.check(lvl, msg)
178}
179
180// Debug logs a message at DebugLevel. The message includes any fields passed
181// at the log site, as well as any fields accumulated on the logger.
182func (log *Logger) Debug(msg string, fields ...Field) {
183 if ce := log.check(DebugLevel, msg); ce != nil {
184 ce.Write(fields...)
185 }
186}
187
188// Info logs a message at InfoLevel. The message includes any fields passed
189// at the log site, as well as any fields accumulated on the logger.
190func (log *Logger) Info(msg string, fields ...Field) {
191 if ce := log.check(InfoLevel, msg); ce != nil {
192 ce.Write(fields...)
193 }
194}
195
196// Warn logs a message at WarnLevel. The message includes any fields passed
197// at the log site, as well as any fields accumulated on the logger.
198func (log *Logger) Warn(msg string, fields ...Field) {
199 if ce := log.check(WarnLevel, msg); ce != nil {
200 ce.Write(fields...)
201 }
202}
203
204// Error logs a message at ErrorLevel. The message includes any fields passed
205// at the log site, as well as any fields accumulated on the logger.
206func (log *Logger) Error(msg string, fields ...Field) {
207 if ce := log.check(ErrorLevel, msg); ce != nil {
208 ce.Write(fields...)
209 }
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.
218func (log *Logger) DPanic(msg string, fields ...Field) {
219 if ce := log.check(DPanicLevel, msg); ce != nil {
220 ce.Write(fields...)
221 }
222}
223
224// Panic logs a message at PanicLevel. The message includes any fields passed
225// at the log site, as well as any fields accumulated on the logger.
226//
227// The logger then panics, even if logging at PanicLevel is disabled.
228func (log *Logger) Panic(msg string, fields ...Field) {
229 if ce := log.check(PanicLevel, msg); ce != nil {
230 ce.Write(fields...)
231 }
232}
233
234// Fatal logs a message at FatalLevel. The message includes any fields passed
235// at the log site, as well as any fields accumulated on the logger.
236//
237// The logger then calls os.Exit(1), even if logging at FatalLevel is
238// disabled.
239func (log *Logger) Fatal(msg string, fields ...Field) {
240 if ce := log.check(FatalLevel, msg); ce != nil {
241 ce.Write(fields...)
242 }
243}
244
245// Sync calls the underlying Core's Sync method, flushing any buffered log
246// entries. Applications should take care to call Sync before exiting.
247func (log *Logger) Sync() error {
248 return log.core.Sync()
249}
250
251// Core returns the Logger's underlying zapcore.Core.
252func (log *Logger) Core() zapcore.Core {
253 return log.core
254}
255
256func (log *Logger) clone() *Logger {
257 copy := *log
258 return &copy
259}
260
261func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
262 // check must always be called directly by a method in the Logger interface
263 // (e.g., Check, Info, Fatal).
264 const callerSkipOffset = 2
265
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000266 // Check the level first to reduce the cost of disabled log calls.
267 // Since Panic and higher may exit, we skip the optimization for those levels.
268 if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) {
269 return nil
270 }
271
Don Newton7577f072020-01-06 12:41:11 -0500272 // Create basic checked entry thru the core; this will be non-nil if the
273 // log message will actually be written somewhere.
274 ent := zapcore.Entry{
275 LoggerName: log.name,
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000276 Time: log.clock.Now(),
Don Newton7577f072020-01-06 12:41:11 -0500277 Level: lvl,
278 Message: msg,
279 }
280 ce := log.core.Check(ent, nil)
281 willWrite := ce != nil
282
283 // Set up any required terminal behavior.
284 switch ent.Level {
285 case zapcore.PanicLevel:
286 ce = ce.Should(ent, zapcore.WriteThenPanic)
287 case zapcore.FatalLevel:
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000288 onFatal := log.onFatal
289 // Noop is the default value for CheckWriteAction, and it leads to
290 // continued execution after a Fatal which is unexpected.
291 if onFatal == zapcore.WriteThenNoop {
292 onFatal = zapcore.WriteThenFatal
293 }
294 ce = ce.Should(ent, onFatal)
Don Newton7577f072020-01-06 12:41:11 -0500295 case zapcore.DPanicLevel:
296 if log.development {
297 ce = ce.Should(ent, zapcore.WriteThenPanic)
298 }
299 }
300
301 // Only do further annotation if we're going to write this message; checked
302 // entries that exist only for terminal behavior don't benefit from
303 // annotation.
304 if !willWrite {
305 return ce
306 }
307
308 // Thread the error output through to the CheckedEntry.
309 ce.ErrorOutput = log.errorOutput
310 if log.addCaller {
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000311 frame, defined := getCallerFrame(log.callerSkip + callerSkipOffset)
312 if !defined {
313 fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC())
Don Newton7577f072020-01-06 12:41:11 -0500314 log.errorOutput.Sync()
315 }
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000316
317 ce.Entry.Caller = zapcore.EntryCaller{
318 Defined: defined,
319 PC: frame.PC,
320 File: frame.File,
321 Line: frame.Line,
322 Function: frame.Function,
323 }
Don Newton7577f072020-01-06 12:41:11 -0500324 }
325 if log.addStack.Enabled(ce.Entry.Level) {
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000326 ce.Entry.Stack = StackSkip("", log.callerSkip+callerSkipOffset).String
Don Newton7577f072020-01-06 12:41:11 -0500327 }
328
329 return ce
330}
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +0000331
332// getCallerFrame gets caller frame. The argument skip is the number of stack
333// frames to ascend, with 0 identifying the caller of getCallerFrame. The
334// boolean ok is false if it was not possible to recover the information.
335//
336// Note: This implementation is similar to runtime.Caller, but it returns the whole frame.
337func getCallerFrame(skip int) (frame runtime.Frame, ok bool) {
338 const skipOffset = 2 // skip getCallerFrame and Callers
339
340 pc := make([]uintptr, 1)
341 numFrames := runtime.Callers(skip+skipOffset, pc)
342 if numFrames < 1 {
343 return
344 }
345
346 frame, _ = runtime.CallersFrames(pc).Next()
347 return frame, frame.PC != 0
348}