Use TimeFieldFormat for Timestamp field

This commit is contained in:
Olivier Poitrey 2017-05-19 22:14:51 -07:00
parent fa2d76dd80
commit 156a4e8b0f
3 changed files with 8 additions and 3 deletions

View File

@ -78,11 +78,14 @@ func appendFloat64(dst []byte, key string, val float64) []byte {
}
func appendTime(dst []byte, key string, t time.Time) []byte {
if TimeFieldFormat == "" {
return appendInt64(dst, key, t.Unix())
}
return append(t.AppendFormat(append(appendKey(dst, key), '"'), TimeFieldFormat), '"')
}
func appendTimestamp(dst []byte) []byte {
return appendInt64(dst, TimestampFieldName, now().Unix())
return appendTime(dst, TimestampFieldName, now())
}
func appendObject(dst []byte, key string, obj interface{}) []byte {

View File

@ -20,6 +20,8 @@ var (
SampleFieldName = "sample"
// TimeFieldFormat defines the time format of the Time field type.
// If set to an empty string, the time is formatted as an UNIX timestamp
// as integer.
TimeFieldFormat = time.RFC3339
)

View File

@ -247,7 +247,7 @@ func TestContextTimestamp(t *testing.T) {
log := New(out).With().Timestamp().Str("foo", "bar").Logger()
log.Log().Msg("hello world")
if got, want := out.String(), `{"time":981173106,"foo":"bar","message":"hello world"}`+"\n"; got != want {
if got, want := out.String(), `{"time":"2001-02-03T04:05:06Z","foo":"bar","message":"hello world"}`+"\n"; got != want {
t.Errorf("invalid log output: got %q, want %q", got, want)
}
}
@ -263,7 +263,7 @@ func TestEventTimestamp(t *testing.T) {
log := New(out).With().Str("foo", "bar").Logger()
log.Log().Timestamp().Msg("hello world")
if got, want := out.String(), `{"foo":"bar","time":981173106,"message":"hello world"}`+"\n"; got != want {
if got, want := out.String(), `{"foo":"bar","time":"2001-02-03T04:05:06Z","message":"hello world"}`+"\n"; got != want {
t.Errorf("invalid log output: got %q, want %q", got, want)
}
}