Skip to content

Commit d18d480

Browse files
trigrabmroote
authored andcommitted
Reformat timestamps in factorio log
1 parent 99e32dd commit d18d480

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

src/factorio/gamelog.go

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package factorio
22

33
import (
4+
"errors"
5+
"log"
6+
"regexp"
7+
"strings"
8+
"time"
9+
410
"github.com/hpcloud/tail"
511
"github.com/mroote/factorio-server-manager/bootstrap"
6-
"log"
712
)
813

9-
func TailLog() ([]string, error) {
14+
func tailLog(filename string) ([]string, error) {
1015
result := []string{}
1116

1217
config := bootstrap.GetConfig()
@@ -21,5 +26,54 @@ func TailLog() ([]string, error) {
2126
result = append(result, line.Text)
2227
}
2328

29+
result = reformatTimestamps(result)
30+
2431
return result, nil
2532
}
33+
34+
func getOffset(line string) (string, error) {
35+
re, _ := regexp.Compile(`^\d+.\d+`)
36+
37+
if !re.MatchString(line) {
38+
log.Printf("This line has no offset", line)
39+
return "error", errors.New(line)
40+
}
41+
42+
offset := re.FindString(line)
43+
44+
return offset, nil
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+
func replaceTimestampInLine(line string, offset string, startTime time.Time) string {
56+
offset, err := getOffset(line)
57+
offsetDuration, _ := time.ParseDuration(offset + "s")
58+
timestamp := startTime.Add(offsetDuration)
59+
60+
if err == nil {
61+
return timestamp.Format("2006-01-02 15:04:05") + ":" + strings.Replace(line, offset, "", 1)
62+
} else {
63+
return line
64+
}
65+
}
66+
67+
func reformatTimestamps(log []string) []string {
68+
firstLine := log[0]
69+
startTime := getStartTime(firstLine)
70+
result := []string{}
71+
72+
for i := range log {
73+
line := strings.TrimLeft(log[i], " \t")
74+
offset, _ := getOffset(line)
75+
result = append(result, replaceTimestampInLine(line, offset, startTime))
76+
}
77+
78+
return result
79+
}

0 commit comments

Comments
 (0)