11package main
22
33import (
4- "log"
4+ "errors"
5+ "log"
6+ "regexp"
7+ "strings"
8+ "time"
59
6- "github.com/hpcloud/tail"
10+ "github.com/hpcloud/tail"
711)
812
13+
914func tailLog (filename string ) ([]string , error ) {
1015 result := []string {}
1116
@@ -19,5 +24,58 @@ func tailLog(filename string) ([]string, error) {
1924 result = append (result , line .Text )
2025 }
2126
22- return result , nil
27+ result = reformatTimestamps (result )
28+
29+ return result , nil
30+ }
31+
32+
33+ func getOffset (line string ) (string , error ) {
34+ re , _ := regexp .Compile (`^\d+.\d+` )
35+
36+ if ! re .MatchString (line ) {
37+ log .Printf ("This line has no offset" , line )
38+ return "error" , errors .New (line )
39+ }
40+
41+ offset := re .FindString (line )
42+
43+ return offset , nil
44+ }
45+
46+
47+ func getStartTime (line string ) (time.Time ) {
48+ re , _ := regexp .Compile (`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}` )
49+ date := string (re .FindString (line ))
50+ startTime , _ := time .Parse (time .RFC3339 , strings .Replace (date , " " , "T" , 1 ) + "Z" )
51+
52+ return startTime
53+ }
54+
55+
56+ func replaceTimestampInLine (line string , offset string , startTime time.Time ) (string ) {
57+ offset , err := getOffset (line )
58+ offsetDuration , _ := time .ParseDuration (offset + "s" )
59+ timestamp := startTime .Add (offsetDuration )
60+
61+ if err == nil {
62+ return timestamp .Format ("2006-01-02 15:04:05" ) + ":" + strings .Replace (line , offset , "" , 1 )
63+ } else {
64+ return line
65+ }
66+ }
67+
68+
69+ func reformatTimestamps (log []string ) ([]string ) {
70+ firstLine := log [0 ]
71+ startTime := getStartTime (firstLine )
72+ result := []string {}
73+
74+ for i := range log {
75+ line := strings .TrimLeft (log [i ], " \t " )
76+ offset , _ := getOffset (line )
77+ result = append (result , replaceTimestampInLine (line , offset , startTime ))
78+ }
79+
80+ return result
2381}
0 commit comments