Skip to content

Commit

Permalink
Add RFC3339NanoFormatter and UnixNanoFormatter (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
errnoh authored and akshayjshah committed Feb 7, 2017
1 parent a5783ee commit c064b5c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions json_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ func EpochFormatter(key string) TimeFormatter {
})
}

// UnixNanoFormatter encodes the entry time as a single int64 with nanosecond
// precision under the provided key.
func UnixNanoFormatter(key string) TimeFormatter {
return TimeFormatter(func(t time.Time) Field {
return Int64(key, t.UnixNano())
})
}

// RFC3339Formatter encodes the entry time as an RFC3339-formatted string under
// the provided key.
func RFC3339Formatter(key string) TimeFormatter {
Expand All @@ -67,6 +75,14 @@ func RFC3339Formatter(key string) TimeFormatter {
})
}

// RFC3339NanoFormatter encodes the entry time as an RFC3339-formatted string
// with nanosecond precision under the provided key.
func RFC3339NanoFormatter(key string) TimeFormatter {
return TimeFormatter(func(t time.Time) Field {
return String(key, t.Format(time.RFC3339Nano))
})
}

// NoTime drops the entry time altogether. It's often useful in testing, since
// it removes the need to stub time.Now.
func NoTime() TimeFormatter {
Expand Down
18 changes: 18 additions & 0 deletions json_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package zap

import (
"testing"
"time"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -60,6 +61,23 @@ func TestTimeFormatters(t *testing.T) {
}
}

func TestNanoTimeFormatters(t *testing.T) {
testtime := time.Date(2017, time.February, 4, 18, 48, 2, 300537459, time.UTC)

tests := []struct {
name string
formatter TimeFormatter
expected Field
}{
{"UnixNanoFormatter", UnixNanoFormatter("the-time"), Int64("the-time", 1486234082300537459)},
{"RFC3339Nano", RFC3339NanoFormatter("ts"), String("ts", "2017-02-04T18:48:02.300537459Z")},
}

for _, tt := range tests {
assert.Equal(t, tt.expected, tt.formatter(testtime), "Unexpected output from TimeFormatter %s.", tt.name)
}
}

func TestLevelFormatters(t *testing.T) {
const lvl = InfoLevel
tests := []struct {
Expand Down

0 comments on commit c064b5c

Please sign in to comment.