1 // Copyright (c) 2016 Uber Technologies, Inc.
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:
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
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
31 "go.uber.org/zap/zapcore"
34 // A Logger provides fast, leveled, structured logging. All methods are safe
35 // for concurrent use.
37 // The Logger is designed for contexts in which every microsecond and every
38 // allocation matters, so its API intentionally favors performance and type
39 // safety over brevity. For most applications, the SugaredLogger strikes a
40 // better balance between performance and ergonomics.
46 errorOutput zapcore.WriteSyncer
49 addStack zapcore.LevelEnabler
54 // New constructs a new Logger from the provided zapcore.Core and Options. If
55 // the passed zapcore.Core is nil, it falls back to using a no-op
58 // This is the most flexible way to construct a Logger, but also the most
59 // verbose. For typical use cases, the highly-opinionated presets
60 // (NewProduction, NewDevelopment, and NewExample) or the Config struct are
63 // For sample code, see the package-level AdvancedConfiguration example.
64 func New(core zapcore.Core, options ...Option) *Logger {
70 errorOutput: zapcore.Lock(os.Stderr),
71 addStack: zapcore.FatalLevel + 1,
73 return log.WithOptions(options...)
76 // NewNop returns a no-op Logger. It never writes out logs or internal errors,
77 // and it never runs user-defined hooks.
79 // Using WithOptions to replace the Core or error output of a no-op Logger can
81 func NewNop() *Logger {
83 core: zapcore.NewNopCore(),
84 errorOutput: zapcore.AddSync(ioutil.Discard),
85 addStack: zapcore.FatalLevel + 1,
89 // NewProduction builds a sensible production Logger that writes InfoLevel and
90 // above logs to standard error as JSON.
92 // It's a shortcut for NewProductionConfig().Build(...Option).
93 func NewProduction(options ...Option) (*Logger, error) {
94 return NewProductionConfig().Build(options...)
97 // NewDevelopment builds a development Logger that writes DebugLevel and above
98 // logs to standard error in a human-friendly format.
100 // It's a shortcut for NewDevelopmentConfig().Build(...Option).
101 func NewDevelopment(options ...Option) (*Logger, error) {
102 return NewDevelopmentConfig().Build(options...)
105 // NewExample builds a Logger that's designed for use in zap's testable
106 // examples. It writes DebugLevel and above logs to standard out as JSON, but
107 // omits the timestamp and calling function to keep example output
108 // short and deterministic.
109 func NewExample(options ...Option) *Logger {
110 encoderCfg := zapcore.EncoderConfig{
114 EncodeLevel: zapcore.LowercaseLevelEncoder,
115 EncodeTime: zapcore.ISO8601TimeEncoder,
116 EncodeDuration: zapcore.StringDurationEncoder,
118 core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel)
119 return New(core).WithOptions(options...)
122 // Sugar wraps the Logger to provide a more ergonomic, but slightly slower,
123 // API. Sugaring a Logger is quite inexpensive, so it's reasonable for a
124 // single application to use both Loggers and SugaredLoggers, converting
125 // between them on the boundaries of performance-sensitive code.
126 func (log *Logger) Sugar() *SugaredLogger {
129 return &SugaredLogger{core}
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 {
142 l.name = strings.Join([]string{l.name, s}, ".")
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 {
151 for _, opt := range opts {
157 // With creates a child logger and adds structured context to it. Fields added
158 // to the child don't affect the parent, and vice versa.
159 func (log *Logger) With(fields ...Field) *Logger {
160 if len(fields) == 0 {
164 l.core = l.core.With(fields)
168 // Check returns a CheckedEntry if logging a message at the specified level
169 // is enabled. It's a completely optional optimization; in high-performance
170 // applications, Check can help avoid allocating a slice to hold fields.
171 func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
172 return log.check(lvl, msg)
175 // Debug logs a message at DebugLevel. The message includes any fields passed
176 // at the log site, as well as any fields accumulated on the logger.
177 func (log *Logger) Debug(msg string, fields ...Field) {
178 if ce := log.check(DebugLevel, msg); ce != nil {
183 // Info logs a message at InfoLevel. The message includes any fields passed
184 // at the log site, as well as any fields accumulated on the logger.
185 func (log *Logger) Info(msg string, fields ...Field) {
186 if ce := log.check(InfoLevel, msg); ce != nil {
191 // Warn logs a message at WarnLevel. The message includes any fields passed
192 // at the log site, as well as any fields accumulated on the logger.
193 func (log *Logger) Warn(msg string, fields ...Field) {
194 if ce := log.check(WarnLevel, msg); ce != nil {
199 // Error logs a message at ErrorLevel. The message includes any fields passed
200 // at the log site, as well as any fields accumulated on the logger.
201 func (log *Logger) Error(msg string, fields ...Field) {
202 if ce := log.check(ErrorLevel, msg); ce != nil {
207 // DPanic logs a message at DPanicLevel. The message includes any fields
208 // passed at the log site, as well as any fields accumulated on the logger.
210 // If the logger is in development mode, it then panics (DPanic means
211 // "development panic"). This is useful for catching errors that are
212 // recoverable, but shouldn't ever happen.
213 func (log *Logger) DPanic(msg string, fields ...Field) {
214 if ce := log.check(DPanicLevel, msg); ce != nil {
219 // Panic logs a message at PanicLevel. The message includes any fields passed
220 // at the log site, as well as any fields accumulated on the logger.
222 // The logger then panics, even if logging at PanicLevel is disabled.
223 func (log *Logger) Panic(msg string, fields ...Field) {
224 if ce := log.check(PanicLevel, msg); ce != nil {
229 // Fatal logs a message at FatalLevel. The message includes any fields passed
230 // at the log site, as well as any fields accumulated on the logger.
232 // The logger then calls os.Exit(1), even if logging at FatalLevel is
234 func (log *Logger) Fatal(msg string, fields ...Field) {
235 if ce := log.check(FatalLevel, msg); ce != nil {
240 // Sync calls the underlying Core's Sync method, flushing any buffered log
241 // entries. Applications should take care to call Sync before exiting.
242 func (log *Logger) Sync() error {
243 return log.core.Sync()
246 // Core returns the Logger's underlying zapcore.Core.
247 func (log *Logger) Core() zapcore.Core {
251 func (log *Logger) clone() *Logger {
256 func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
257 // check must always be called directly by a method in the Logger interface
258 // (e.g., Check, Info, Fatal).
259 const callerSkipOffset = 2
261 // Create basic checked entry thru the core; this will be non-nil if the
262 // log message will actually be written somewhere.
263 ent := zapcore.Entry{
264 LoggerName: log.name,
269 ce := log.core.Check(ent, nil)
270 willWrite := ce != nil
272 // Set up any required terminal behavior.
274 case zapcore.PanicLevel:
275 ce = ce.Should(ent, zapcore.WriteThenPanic)
276 case zapcore.FatalLevel:
277 ce = ce.Should(ent, zapcore.WriteThenFatal)
278 case zapcore.DPanicLevel:
280 ce = ce.Should(ent, zapcore.WriteThenPanic)
284 // Only do further annotation if we're going to write this message; checked
285 // entries that exist only for terminal behavior don't benefit from
291 // Thread the error output through to the CheckedEntry.
292 ce.ErrorOutput = log.errorOutput
294 ce.Entry.Caller = zapcore.NewEntryCaller(runtime.Caller(log.callerSkip + callerSkipOffset))
295 if !ce.Entry.Caller.Defined {
296 fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", time.Now().UTC())
297 log.errorOutput.Sync()
300 if log.addStack.Enabled(ce.Entry.Level) {
301 ce.Entry.Stack = Stack("").String