1 // Copyright (c) 2017 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
26 "go.uber.org/zap/zapcore"
29 var _errArrayElemPool = sync.Pool{New: func() interface{} {
30 return &errArrayElem{}
33 // Error is shorthand for the common idiom NamedError("error", err).
34 func Error(err error) Field {
35 return NamedError("error", err)
38 // NamedError constructs a field that lazily stores err.Error() under the
39 // provided key. Errors which also implement fmt.Formatter (like those produced
40 // by github.com/pkg/errors) will also have their verbose representation stored
41 // under key+"Verbose". If passed a nil error, the field is a no-op.
43 // For the common case in which the key is simply "error", the Error function
44 // is shorter and less repetitive.
45 func NamedError(key string, err error) Field {
49 return Field{Key: key, Type: zapcore.ErrorType, Interface: err}
54 func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error {
59 // To represent each error as an object with an "error" attribute and
60 // potentially an "errorVerbose" attribute, we need to wrap it in a
61 // type that implements LogObjectMarshaler. To prevent this from
62 // allocating, pool the wrapper type.
63 elem := _errArrayElemPool.Get().(*errArrayElem)
65 arr.AppendObject(elem)
67 _errArrayElemPool.Put(elem)
72 type errArrayElem struct {
76 func (e *errArrayElem) MarshalLogObject(enc zapcore.ObjectEncoder) error {
77 // Re-use the error field's logic, which supports non-standard error types.
78 Error(e.error).AddTo(enc)