forked from uber-go/zap
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move error logging code to error.go (uber-go#457)
This gives errors their own file like array.go before we add more complex handling for error types. I also moved the tests for errors to error_test to be consistent. Feel free to close this if you don't want to organize the code this way, in which case the multierr integration will be in field.go.
- Loading branch information
1 parent
02029bc
commit 0a01722
Showing
6 changed files
with
179 additions
and
91 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
// Copyright (c) 2016 Uber Technologies, Inc. | ||
// | ||
// Permission is hereby granted, free of charge, to any person obtaining a copy | ||
// of this software and associated documentation files (the "Software"), to deal | ||
// in the Software without restriction, including without limitation the rights | ||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
// copies of the Software, and to permit persons to whom the Software is | ||
// furnished to do so, subject to the following conditions: | ||
// | ||
// The above copyright notice and this permission notice shall be included in | ||
// all copies or substantial portions of the Software. | ||
// | ||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
// THE SOFTWARE. | ||
|
||
package zap | ||
|
||
import ( | ||
"sync" | ||
|
||
"go.uber.org/zap/zapcore" | ||
) | ||
|
||
var _errArrayElemPool = sync.Pool{New: func() interface{} { | ||
return &errArrayElem{} | ||
}} | ||
|
||
// Error is shorthand for the common idiom NamedError("error", err). | ||
func Error(err error) zapcore.Field { | ||
return NamedError("error", err) | ||
} | ||
|
||
// NamedError constructs a field that lazily stores err.Error() under the | ||
// provided key. Errors which also implement fmt.Formatter (like those produced | ||
// by github.com/pkg/errors) will also have their verbose representation stored | ||
// under key+"Verbose". If passed a nil error, the field is a no-op. | ||
// | ||
// For the common case in which the key is simply "error", the Error function | ||
// is shorter and less repetitive. | ||
func NamedError(key string, err error) zapcore.Field { | ||
if err == nil { | ||
return Skip() | ||
} | ||
return zapcore.Field{Key: key, Type: zapcore.ErrorType, Interface: err} | ||
} | ||
|
||
type errArray []error | ||
|
||
func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { | ||
for i := range errs { | ||
if errs[i] == nil { | ||
continue | ||
} | ||
// To represent each error as an object with an "error" attribute and | ||
// potentially an "errorVerbose" attribute, we need to wrap it in a | ||
// type that implements LogObjectMarshaler. To prevent this from | ||
// allocating, pool the wrapper type. | ||
elem := _errArrayElemPool.Get().(*errArrayElem) | ||
elem.error = errs[i] | ||
arr.AppendObject(elem) | ||
elem.error = nil | ||
_errArrayElemPool.Put(elem) | ||
} | ||
return nil | ||
} | ||
|
||
type errArrayElem struct { | ||
error | ||
} | ||
|
||
func (e *errArrayElem) MarshalLogObject(enc zapcore.ObjectEncoder) error { | ||
// Re-use the error field's logic, which supports non-standard error types. | ||
Error(e.error).AddTo(enc) | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
// Copyright (c) 2016 Uber Technologies, Inc. | ||
// | ||
// Permission is hereby granted, free of charge, to any person obtaining a copy | ||
// of this software and associated documentation files (the "Software"), to deal | ||
// in the Software without restriction, including without limitation the rights | ||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
// copies of the Software, and to permit persons to whom the Software is | ||
// furnished to do so, subject to the following conditions: | ||
// | ||
// The above copyright notice and this permission notice shall be included in | ||
// all copies or substantial portions of the Software. | ||
// | ||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
// THE SOFTWARE. | ||
|
||
package zap | ||
|
||
import ( | ||
"errors" | ||
"testing" | ||
|
||
"go.uber.org/zap/zapcore" | ||
|
||
richErrors "github.com/pkg/errors" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestErrorConstructors(t *testing.T) { | ||
fail := errors.New("fail") | ||
|
||
tests := []struct { | ||
name string | ||
field zapcore.Field | ||
expect zapcore.Field | ||
}{ | ||
{"Error", Skip(), Error(nil)}, | ||
{"Error", zapcore.Field{Key: "error", Type: zapcore.ErrorType, Interface: fail}, Error(fail)}, | ||
{"NamedError", Skip(), NamedError("foo", nil)}, | ||
{"NamedError", zapcore.Field{Key: "foo", Type: zapcore.ErrorType, Interface: fail}, NamedError("foo", fail)}, | ||
{"Any:Error", Any("k", errors.New("v")), NamedError("k", errors.New("v"))}, | ||
{"Any:Errors", Any("k", []error{errors.New("v")}), Errors("k", []error{errors.New("v")})}, | ||
} | ||
|
||
for _, tt := range tests { | ||
if !assert.Equal(t, tt.expect, tt.field, "Unexpected output from convenience field constructor %s.", tt.name) { | ||
t.Logf("type expected: %T\nGot: %T", tt.expect.Interface, tt.field.Interface) | ||
} | ||
assertCanBeReused(t, tt.field) | ||
} | ||
} | ||
|
||
func TestErrorArrayConstructor(t *testing.T) { | ||
tests := []struct { | ||
desc string | ||
field zapcore.Field | ||
expected []interface{} | ||
}{ | ||
{"empty errors", Errors("", []error{}), []interface{}(nil)}, | ||
{ | ||
"errors", | ||
Errors("", []error{nil, errors.New("foo"), nil, errors.New("bar")}), | ||
[]interface{}{map[string]interface{}{"error": "foo"}, map[string]interface{}{"error": "bar"}}, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
enc := zapcore.NewMapObjectEncoder() | ||
tt.field.Key = "k" | ||
tt.field.AddTo(enc) | ||
assert.Equal(t, tt.expected, enc.Fields["k"], "%s: unexpected map contents.", tt.desc) | ||
assert.Equal(t, 1, len(enc.Fields), "%s: found extra keys in map: %v", tt.desc, enc.Fields) | ||
} | ||
} | ||
|
||
func TestErrorsArraysHandleRichErrors(t *testing.T) { | ||
errs := []error{richErrors.New("egad")} | ||
|
||
enc := zapcore.NewMapObjectEncoder() | ||
Errors("k", errs).AddTo(enc) | ||
assert.Equal(t, 1, len(enc.Fields), "Expected only top-level field.") | ||
|
||
val := enc.Fields["k"] | ||
arr, ok := val.([]interface{}) | ||
require.True(t, ok, "Expected top-level field to be an array.") | ||
require.Equal(t, 1, len(arr), "Expected only one error object in array.") | ||
|
||
serialized := arr[0] | ||
errMap, ok := serialized.(map[string]interface{}) | ||
require.True(t, ok, "Expected serialized error to be a map, got %T.", serialized) | ||
assert.Equal(t, "egad", errMap["error"], "Unexpected standard error string.") | ||
assert.Contains(t, errMap["errorVerbose"], "egad", "Verbose error string should be a superset of standard error.") | ||
assert.Contains(t, errMap["errorVerbose"], "TestErrorsArraysHandleRichErrors", "Verbose error string should contain a stacktrace.") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters