Add TimeDiff event method
This commit is contained in:
parent
3f6ca6688c
commit
9889521807
17
event.go
17
event.go
|
@ -278,7 +278,7 @@ func (e *Event) Time(key string, t time.Time) *Event {
|
|||
return e
|
||||
}
|
||||
|
||||
// Dur adds the fields key with duration d stored as zerolog.DurationFieldUnit.
|
||||
// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit.
|
||||
// If zerolog.DurationFieldInteger is true, durations are rendered as integer
|
||||
// instead of float.
|
||||
func (e *Event) Dur(key string, d time.Duration) *Event {
|
||||
|
@ -289,6 +289,21 @@ func (e *Event) Dur(key string, d time.Duration) *Event {
|
|||
return e
|
||||
}
|
||||
|
||||
// TimeDiff adds the field key with positive duration between time t and start.
|
||||
// If time t is not greater than start, duration will be 0.
|
||||
// Duration format follows the same principle as Dur().
|
||||
func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event {
|
||||
if !e.enabled {
|
||||
return e
|
||||
}
|
||||
var d time.Duration
|
||||
if t.After(start) {
|
||||
d = t.Sub(start)
|
||||
}
|
||||
e.buf = appendDuration(e.buf, key, d)
|
||||
return e
|
||||
}
|
||||
|
||||
// Interface adds the field key with i marshaled using reflection.
|
||||
func (e *Event) Interface(key string, i interface{}) *Event {
|
||||
if !e.enabled {
|
||||
|
|
|
@ -119,9 +119,11 @@ func TestFields(t *testing.T) {
|
|||
Uint64("uint64", 10).
|
||||
Float32("float32", 11).
|
||||
Float64("float64", 12).
|
||||
Dur("dur", 1*time.Second).
|
||||
Time("time", time.Time{}).
|
||||
TimeDiff("diff", time.Now(), time.Now().Add(-10*time.Second)).
|
||||
Msg("")
|
||||
if got, want := out.String(), `{"foo":"bar","error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"time":"0001-01-01T00:00:00Z"}`+"\n"; got != want {
|
||||
if got, want := out.String(), `{"foo":"bar","error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want {
|
||||
t.Errorf("invalid log output: got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
@ -146,7 +148,9 @@ func TestFieldsDisabled(t *testing.T) {
|
|||
Uint64("uint64", 10).
|
||||
Float32("float32", 11).
|
||||
Float64("float64", 12).
|
||||
Dur("dur", 1*time.Second).
|
||||
Time("time", time.Time{}).
|
||||
TimeDiff("diff", time.Now(), time.Now().Add(-10*time.Second)).
|
||||
Msg("")
|
||||
if got, want := out.String(), ""; got != want {
|
||||
t.Errorf("invalid log output: got %q, want %q", got, want)
|
||||
|
|
Loading…
Reference in New Issue