Skip to content

Commit 5445cd5

Browse files
authored
281: Support toTimestamp template function (#282)
Co-authored-by: Will Anderson <will.anderson@vivint.com>
1 parent 26839e4 commit 5445cd5

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ functions](https://golang.org/pkg/text/template/#hdr-Functions)):
160160
| `extjson` | `string` | Parse the object as json and output colorized json |
161161
| `ppextjson` | `string` | Parse the object as json and output pretty-print colorized json |
162162
| `toRFC3339Nano` | `object` | Parse timestamp (string, int, json.Number) and output it using RFC3339Nano format |
163+
| `toTimestamp` | `object, string [, string]` | Parse timestamp (string, int, json.Number) and output it using the given layout in the timezone that is optionally given (defaults to UTC). |
163164
| `levelColor` | `string` | Print log level using appropriate color |
164165
| `colorBlack` | `string` | Print text using black color |
165166
| `colorRed` | `string` | Print text using red color |

cmd/cmd.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,24 @@ func (o *options) generateTemplate() (*template.Template, error) {
488488
"toUTC": func(ts any) time.Time {
489489
return cast.ToTime(ts).UTC()
490490
},
491+
"toTimestamp": func(ts any, layout string, optionalTZ ...string) (string, error) {
492+
t, parseErr := cast.ToTimeE(ts)
493+
if parseErr != nil {
494+
return "", parseErr
495+
}
496+
497+
var tz string
498+
if len(optionalTZ) > 0 {
499+
tz = optionalTZ[0]
500+
}
501+
502+
loc, loadErr := time.LoadLocation(tz)
503+
if loadErr != nil {
504+
return "", loadErr
505+
}
506+
507+
return t.In(loc).Format(layout), nil
508+
},
491509
"color": func(color color.Color, text string) string {
492510
return color.SprintFunc()(text)
493511
},

cmd/cmd_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,28 @@ func TestOptionsGenerateTemplate(t *testing.T) {
376376
"pod1 container1 [1970-01-01T00:02:03Z] INFO template message",
377377
false,
378378
},
379+
{
380+
"template-to-timestamp-with-timezone",
381+
func() *options {
382+
o := NewOptions(streams)
383+
o.template = `{{ toTimestamp .Message "Jan 02 2006 15:04 MST" "US/Eastern" }}`
384+
return o
385+
}(),
386+
`2024-01-01T05:00:00`,
387+
`Jan 01 2024 00:00 EST`,
388+
false,
389+
},
390+
{
391+
"template-to-timestamp-without-timezone",
392+
func() *options {
393+
o := NewOptions(streams)
394+
o.template = `{{ toTimestamp .Message "Jan 02 2006 15:04 MST" }}`
395+
return o
396+
}(),
397+
`2024-01-01T05:00:00`,
398+
`Jan 01 2024 05:00 UTC`,
399+
false,
400+
},
379401
}
380402

381403
for _, tt := range tests {

0 commit comments

Comments
 (0)