Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added zapcore.TimeEncoderOfLayout #629

Merged
merged 11 commits into from Jul 7, 2020
15 changes: 14 additions & 1 deletion zapcore/encoder.go
Expand Up @@ -21,6 +21,7 @@
package zapcore

import (
"strings"
"time"

"go.uber.org/zap/buffer"
Expand Down Expand Up @@ -151,15 +152,25 @@ func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) {
encodeTimeLayout(t, time.RFC3339Nano, enc)
}

// TimeEncoderOfFormat returns TimeEncoder which serializes a time.Time using
// given format.
func TimeEncoderOfFormat(format string) TimeEncoder {
return func(t time.Time, enc PrimitiveArrayEncoder) {
tmshn marked this conversation as resolved.
Show resolved Hide resolved
encodeTimeLayout(t, format, enc)
}
}

// UnmarshalText unmarshals text to a TimeEncoder.
// "rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder.
// "rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder.
// "iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder.
// "millis" is unmarshaled to EpochMillisTimeEncoder.
// "nanos" is unmarshaled to EpochNanosEncoder.
// "format=<time-layout-format>" is unmarshaled to TimeEncoder with given format.
// Anything else is unmarshaled to EpochTimeEncoder.
func (e *TimeEncoder) UnmarshalText(text []byte) error {
switch string(text) {
vals := strings.SplitAfterN(string(text), "=", 2)
switch vals[0] {
case "rfc3339nano", "RFC3339Nano":
*e = RFC3339NanoTimeEncoder
case "rfc3339", "RFC3339":
Expand All @@ -170,6 +181,8 @@ func (e *TimeEncoder) UnmarshalText(text []byte) error {
*e = EpochMillisTimeEncoder
case "nanos":
*e = EpochNanosTimeEncoder
case "format=":
*e = TimeEncoderOfFormat(vals[1])
tmshn marked this conversation as resolved.
Show resolved Hide resolved
default:
*e = EpochTimeEncoder
}
Expand Down
1 change: 1 addition & 0 deletions zapcore/encoder_test.go
Expand Up @@ -530,6 +530,7 @@ func TestTimeEncoders(t *testing.T) {
{"ISO8601", "1970-01-01T00:01:40.050Z"},
{"millis", 100050.005},
{"nanos", int64(100050005000)},
{"format=06/01/02 03:04pm", "70/01/01 12:01am"},
{"", 100.050005},
{"something-random", 100.050005},
{"rfc3339", "1970-01-01T00:01:40Z"},
Expand Down