1
1
package main
2
2
3
3
import (
4
- "errors"
5
4
"log"
6
5
"regexp"
7
6
"strings"
@@ -10,6 +9,11 @@ import (
10
9
"github.com/hpcloud/tail"
11
10
)
12
11
12
+ // point of time when logging started
13
+ var startTime time.Time
14
+
15
+ // set this to toggle log reformat of timestamps
16
+ var reformatTimestampsEnabled = true
13
17
14
18
func tailLog (filename string ) ([]string , error ) {
15
19
result := []string {}
@@ -24,57 +28,39 @@ func tailLog(filename string) ([]string, error) {
24
28
result = append (result , line .Text )
25
29
}
26
30
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 )
31
+ if reformatTimestampsEnabled {
32
+ result = reformatTimestamps (result )
39
33
}
40
34
41
- offset := re .FindString (line )
42
-
43
- return offset , nil
35
+ return result , nil
44
36
}
45
37
46
-
47
- func getStartTime (line string ) (time.Time ) {
38
+ func getStartTime (log []string ) {
48
39
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
40
+ date := string (re .FindString (log [0 ]))
41
+ startTime , _ = time .Parse (time .RFC3339 , strings .Replace (date , " " , "T" , 1 ) + "Z" )
53
42
}
54
43
55
-
56
- func replaceTimestampInLine (line string , offset string , startTime time.Time ) (string ) {
57
- offset , err := getOffset (line )
58
- offsetDuration , _ := time .ParseDuration (offset + "s" )
44
+ // convert an offset timestamp from the log to a human readable timestamp
45
+ func offsetToTimestamp (offset string ) (string ) {
46
+ offsetDuration , err := time .ParseDuration (offset + "s" )
59
47
timestamp := startTime .Add (offsetDuration )
60
48
61
49
if err == nil {
62
- return timestamp .Format ("2006-01-02 15:04:05" ) + ":" + strings .Replace (line , offset , "" , 1 )
50
+ return timestamp .Format ("2006-01-02 15:04:05" ) + ":" + strings .Replace (offset , offset , "" , 1 )
63
51
} else {
64
- return line
52
+ return offset
65
53
}
66
54
}
67
55
68
-
69
56
func reformatTimestamps (log []string ) ([]string ) {
70
- firstLine := log [0 ]
71
- startTime := getStartTime (firstLine )
57
+ getStartTime (log )
72
58
result := []string {}
73
59
74
60
for i := range log {
75
61
line := strings .TrimLeft (log [i ], " \t " )
76
- offset , _ := getOffset ( line )
77
- result = append (result , replaceTimestampInLine (line , offset , startTime ))
62
+ re , _ := regexp . Compile ( `^\d+\.\d+` )
63
+ result = append (result , re . ReplaceAllStringFunc (line , offsetToTimestamp ))
78
64
}
79
65
80
66
return result
0 commit comments