divyadesai | 1900913 | 2020-03-04 12:58:08 +0000 | [diff] [blame] | 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 | |
| 21 | package zap |
| 22 | |
| 23 | import ( |
| 24 | "fmt" |
| 25 | "io/ioutil" |
| 26 | "os" |
| 27 | "runtime" |
| 28 | "strings" |
| 29 | "time" |
| 30 | |
| 31 | "go.uber.org/zap/zapcore" |
| 32 | ) |
| 33 | |
| 34 | // A Logger provides fast, leveled, structured logging. All methods are safe |
| 35 | // for concurrent use. |
| 36 | // |
| 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. |
| 41 | type Logger struct { |
| 42 | core zapcore.Core |
| 43 | |
| 44 | development bool |
| 45 | name string |
| 46 | errorOutput zapcore.WriteSyncer |
| 47 | |
| 48 | addCaller bool |
| 49 | addStack zapcore.LevelEnabler |
| 50 | |
| 51 | callerSkip int |
| 52 | } |
| 53 | |
| 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 |
| 56 | // implementation. |
| 57 | // |
| 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 |
| 61 | // more convenient. |
| 62 | // |
| 63 | // For sample code, see the package-level AdvancedConfiguration example. |
| 64 | func New(core zapcore.Core, options ...Option) *Logger { |
| 65 | if core == nil { |
| 66 | return NewNop() |
| 67 | } |
| 68 | log := &Logger{ |
| 69 | core: core, |
| 70 | errorOutput: zapcore.Lock(os.Stderr), |
| 71 | addStack: zapcore.FatalLevel + 1, |
| 72 | } |
| 73 | return log.WithOptions(options...) |
| 74 | } |
| 75 | |
| 76 | // NewNop returns a no-op Logger. It never writes out logs or internal errors, |
| 77 | // and it never runs user-defined hooks. |
| 78 | // |
| 79 | // Using WithOptions to replace the Core or error output of a no-op Logger can |
| 80 | // re-enable logging. |
| 81 | func NewNop() *Logger { |
| 82 | return &Logger{ |
| 83 | core: zapcore.NewNopCore(), |
| 84 | errorOutput: zapcore.AddSync(ioutil.Discard), |
| 85 | addStack: zapcore.FatalLevel + 1, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // NewProduction builds a sensible production Logger that writes InfoLevel and |
| 90 | // above logs to standard error as JSON. |
| 91 | // |
| 92 | // It's a shortcut for NewProductionConfig().Build(...Option). |
| 93 | func NewProduction(options ...Option) (*Logger, error) { |
| 94 | return NewProductionConfig().Build(options...) |
| 95 | } |
| 96 | |
| 97 | // NewDevelopment builds a development Logger that writes DebugLevel and above |
| 98 | // logs to standard error in a human-friendly format. |
| 99 | // |
| 100 | // It's a shortcut for NewDevelopmentConfig().Build(...Option). |
| 101 | func NewDevelopment(options ...Option) (*Logger, error) { |
| 102 | return NewDevelopmentConfig().Build(options...) |
| 103 | } |
| 104 | |
| 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{ |
| 111 | MessageKey: "msg", |
| 112 | LevelKey: "level", |
| 113 | NameKey: "logger", |
| 114 | EncodeLevel: zapcore.LowercaseLevelEncoder, |
| 115 | EncodeTime: zapcore.ISO8601TimeEncoder, |
| 116 | EncodeDuration: zapcore.StringDurationEncoder, |
| 117 | } |
| 118 | core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel) |
| 119 | return New(core).WithOptions(options...) |
| 120 | } |
| 121 | |
| 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 { |
| 127 | core := log.clone() |
| 128 | core.callerSkip += 2 |
| 129 | return &SugaredLogger{core} |
| 130 | } |
| 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 | |
| 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 | |
| 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 { |
| 161 | return log |
| 162 | } |
| 163 | l := log.clone() |
| 164 | l.core = l.core.With(fields) |
| 165 | return l |
| 166 | } |
| 167 | |
| 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) |
| 173 | } |
| 174 | |
| 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 { |
| 179 | ce.Write(fields...) |
| 180 | } |
| 181 | } |
| 182 | |
| 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 { |
| 187 | ce.Write(fields...) |
| 188 | } |
| 189 | } |
| 190 | |
| 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 { |
| 195 | ce.Write(fields...) |
| 196 | } |
| 197 | } |
| 198 | |
| 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 { |
| 203 | ce.Write(fields...) |
| 204 | } |
| 205 | } |
| 206 | |
| 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. |
| 209 | // |
| 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 { |
| 215 | ce.Write(fields...) |
| 216 | } |
| 217 | } |
| 218 | |
| 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. |
| 221 | // |
| 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 { |
| 225 | ce.Write(fields...) |
| 226 | } |
| 227 | } |
| 228 | |
| 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. |
| 231 | // |
| 232 | // The logger then calls os.Exit(1), even if logging at FatalLevel is |
| 233 | // disabled. |
| 234 | func (log *Logger) Fatal(msg string, fields ...Field) { |
| 235 | if ce := log.check(FatalLevel, msg); ce != nil { |
| 236 | ce.Write(fields...) |
| 237 | } |
| 238 | } |
| 239 | |
| 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() |
| 244 | } |
| 245 | |
| 246 | // Core returns the Logger's underlying zapcore.Core. |
| 247 | func (log *Logger) Core() zapcore.Core { |
| 248 | return log.core |
| 249 | } |
| 250 | |
| 251 | func (log *Logger) clone() *Logger { |
| 252 | copy := *log |
| 253 | return © |
| 254 | } |
| 255 | |
| 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 |
| 260 | |
| 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, |
| 265 | Time: time.Now(), |
| 266 | Level: lvl, |
| 267 | Message: msg, |
| 268 | } |
| 269 | ce := log.core.Check(ent, nil) |
| 270 | willWrite := ce != nil |
| 271 | |
| 272 | // Set up any required terminal behavior. |
| 273 | switch ent.Level { |
| 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: |
| 279 | if log.development { |
| 280 | ce = ce.Should(ent, zapcore.WriteThenPanic) |
| 281 | } |
| 282 | } |
| 283 | |
| 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 |
| 286 | // annotation. |
| 287 | if !willWrite { |
| 288 | return ce |
| 289 | } |
| 290 | |
| 291 | // Thread the error output through to the CheckedEntry. |
| 292 | ce.ErrorOutput = log.errorOutput |
| 293 | if log.addCaller { |
| 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() |
| 298 | } |
| 299 | } |
| 300 | if log.addStack.Enabled(ce.Entry.Level) { |
| 301 | ce.Entry.Stack = Stack("").String |
| 302 | } |
| 303 | |
| 304 | return ce |
| 305 | } |