2015-12-15 19:49:41 +00:00
|
|
|
// Package jsonlog provides helper functions to parse and print time (time.Time) as JSON.
|
|
|
|
package jsonlog
|
2014-09-15 18:44:58 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2014-10-06 19:27:56 +00:00
|
|
|
// RFC3339NanoFixed is our own version of RFC339Nano because we want one
|
2014-09-15 18:44:58 +00:00
|
|
|
// that pads the nano seconds part with zeros to ensure
|
|
|
|
// the timestamps are aligned in the logs.
|
|
|
|
RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
|
2014-10-06 19:27:56 +00:00
|
|
|
// JSONFormat is the format used by FastMarshalJSON
|
|
|
|
JSONFormat = `"` + time.RFC3339Nano + `"`
|
2014-09-15 18:44:58 +00:00
|
|
|
)
|
|
|
|
|
2015-12-15 19:49:41 +00:00
|
|
|
// FastTimeMarshalJSON avoids one of the extra allocations that
|
2014-10-06 19:27:56 +00:00
|
|
|
// time.MarshalJSON is making.
|
2015-12-15 19:49:41 +00:00
|
|
|
func FastTimeMarshalJSON(t time.Time) (string, error) {
|
2014-09-15 18:44:58 +00:00
|
|
|
if y := t.Year(); y < 0 || y >= 10000 {
|
|
|
|
// RFC 3339 is clear that years are 4 digits exactly.
|
|
|
|
// See golang.org/issue/4556#c15 for more discussion.
|
2014-10-06 19:27:56 +00:00
|
|
|
return "", errors.New("time.MarshalJSON: year outside of range [0,9999]")
|
2014-09-15 18:44:58 +00:00
|
|
|
}
|
|
|
|
return t.Format(JSONFormat), nil
|
|
|
|
}
|