Add ErrorHandler global to allow handling of write errors
This commit is contained in:
parent
848482bc3d
commit
8747b7b3a5
|
@ -479,6 +479,7 @@ Some settings can be changed and will by applied to all loggers:
|
|||
// using the Dur method.
|
||||
* `DurationFieldUnit`: Sets the unit of the fields added by `Dur` (default: `time.Millisecond`).
|
||||
* `DurationFieldInteger`: If set to true, `Dur` fields are formatted as integers instead of floats.
|
||||
* `ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.
|
||||
|
||||
## Field Types
|
||||
|
||||
|
|
4
event.go
4
event.go
|
@ -137,8 +137,12 @@ func (e *Event) msg(msg string) {
|
|||
defer e.done(msg)
|
||||
}
|
||||
if err := e.write(); err != nil {
|
||||
if ErrorHandler != nil {
|
||||
ErrorHandler(err)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fields is a helper function to use a map to set fields using type assertion.
|
||||
|
|
|
@ -37,6 +37,11 @@ var (
|
|||
// DurationFieldInteger renders Dur fields as integer instead of float if
|
||||
// set to true.
|
||||
DurationFieldInteger = false
|
||||
|
||||
// ErrorHandler is called whenever zerolog fails to write an event on its
|
||||
// output. If not set, an error is printed on the stderr. This handler must
|
||||
// be thread safe and non-blocking.
|
||||
ErrorHandler func(err error)
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
21
log_test.go
21
log_test.go
|
@ -640,3 +640,24 @@ func TestErrorMarshalFunc(t *testing.T) {
|
|||
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
type errWriter struct {
|
||||
error
|
||||
}
|
||||
|
||||
func (w errWriter) Write(p []byte) (n int, err error) {
|
||||
return 0, w.error
|
||||
}
|
||||
|
||||
func TestErrorHandler(t *testing.T) {
|
||||
var got error
|
||||
want := errors.New("write error")
|
||||
ErrorHandler = func(err error) {
|
||||
got = err
|
||||
}
|
||||
log := New(errWriter{want})
|
||||
log.Log().Msg("test")
|
||||
if got != want {
|
||||
t.Errorf("ErrorHandler err = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue