-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
formatter_time.go
63 lines (49 loc) · 1.48 KB
/
formatter_time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package slogformatter
import (
"time"
"log/slog"
"github.com/samber/lo"
)
// TimeFormatter transforms a `time.Time` into a readable string.
func TimeFormatter(timeFormat string, location *time.Location) Formatter {
if timeFormat == "" {
timeFormat = time.RFC3339
}
return FormatByKind(slog.KindTime, func(value slog.Value) slog.Value {
t := value.Time()
if location != nil {
t = t.In(location)
}
return slog.StringValue(t.Format(timeFormat))
})
}
// UnixTimestampFormatter transforms a `time.Time` into a unix timestamp.
func UnixTimestampFormatter(precision time.Duration) Formatter {
if !lo.Contains([]time.Duration{time.Nanosecond, time.Microsecond, time.Millisecond, time.Second}, precision) {
panic("slog-formatter: unexpected precision")
}
return FormatByKind(slog.KindTime, func(value slog.Value) slog.Value {
t := value.Time()
switch precision {
case time.Nanosecond:
return slog.Int64Value(t.UnixNano())
case time.Microsecond:
return slog.Int64Value(t.UnixMicro())
case time.Millisecond:
return slog.Int64Value(t.UnixMilli())
case time.Second:
return slog.Int64Value(t.Unix())
}
panic("slog-formatter: unexpected precision")
})
}
// TimezoneConverter set a `time.Time` to a different timezone.
func TimezoneConverter(location *time.Location) Formatter {
return FormatByKind(slog.KindTime, func(value slog.Value) slog.Value {
t := value.Time()
if location == nil {
location = time.UTC
}
return slog.TimeValue(t.In(location))
})
}