Skip to content

Commit

Permalink
Support for unix int timestamps in string values
Browse files Browse the repository at this point in the history
  • Loading branch information
jaspeen authored and aybabtme committed Oct 25, 2024
1 parent c4d95a5 commit 5019226
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
3 changes: 3 additions & 0 deletions logfmt_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ func (h *LogfmtHandler) UnmarshalLogfmt(data []byte) bool {
val := dec.Value()
if h.Time.IsZero() {
foundTime := checkEachUntilFound(h.Opts.TimeFields, func(field string) bool {
if !bytes.Equal(key, []byte(field)) {
return false
}
time, ok := tryParseTime(string(val))
if ok {
h.Time = time
Expand Down
6 changes: 6 additions & 0 deletions time_parse.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package humanlog

import (
"strconv"
"time"
)

Expand Down Expand Up @@ -54,6 +55,11 @@ func tryParseTime(value interface{}) (time.Time, bool) {
return t, true
}
}
// try to parse unix time number from string
floatVal, err := strconv.ParseFloat(v, 64)
if err == nil {
return parseTimeFloat64(floatVal), true
}
case float32:
return parseTimeFloat64(float64(v)), true
case float64:
Expand Down
40 changes: 40 additions & 0 deletions time_parse_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package humanlog

import (
"fmt"
"testing"
"time"
)

func TestTimeParseFloat64(t *testing.T) {
Expand Down Expand Up @@ -34,3 +36,41 @@ func TestTimeParseFloat64(t *testing.T) {
}
})
}

func TestTryParseFloatTime(t *testing.T) {
testTime := time.Now()

t.Run("microseconds", func(t *testing.T) {
actualTime, ok := tryParseTime(fmt.Sprintf("%d", testTime.UnixMicro()))
if !ok {
t.Fatal("time not parsed")
}

if actualTime.UnixMicro() != testTime.UnixMicro() {
t.Fatalf("time not equal: %d != %d", actualTime.UnixMicro(), testTime.UnixMicro())
}
})

t.Run("milliseconds", func(t *testing.T) {
actualTime, ok := tryParseTime(fmt.Sprintf("%d", testTime.UnixMilli()))
if !ok {
t.Fatal("time not parsed")
}

if actualTime.UnixMilli() != testTime.UnixMilli() {
t.Fatalf("time not equal: %d != %d", actualTime.UnixMilli(), testTime.UnixMilli())
}
})

t.Run("seconds", func(t *testing.T) {
actualTime, ok := tryParseTime(fmt.Sprintf("%d", testTime.Unix()))
if !ok {
t.Fatal("time not parsed")
}

if actualTime.Unix() != testTime.Unix() {
t.Fatalf("time not equal: %d != %d", actualTime.Unix(), testTime.Unix())
}
})

}

0 comments on commit 5019226

Please sign in to comment.