-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathgamelog.go
80 lines (60 loc) · 1.74 KB
/
gamelog.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package factorio
import (
"errors"
"log"
"regexp"
"strings"
"time"
"github.com/hpcloud/tail"
"github.com/OpenFactorioServerManager/factorio-server-manager/bootstrap"
)
// TailLog tails the Factorio game log file
func TailLog(filename string) ([]string, error) {
var result []string
config := bootstrap.GetConfig()
t, err := tail.TailFile(config.FactorioLog, tail.Config{Follow: false})
if err != nil {
log.Printf("Error tailing log %s", err)
return result, err
}
for line := range t.Lines {
result = append(result, line.Text)
}
result = reformatTimestamps(result)
return result, nil
}
func getOffset(line string) (string, error) {
re, _ := regexp.Compile(`^\d+.\d+`)
if !re.MatchString(line) {
log.Printf("This line has no offset %v\n", line)
return "error", errors.New(line)
}
offset := re.FindString(line)
return offset, nil
}
func getStartTime(line string) time.Time {
re, _ := regexp.Compile(`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}`)
date := re.FindString(line)
startTime, _ := time.Parse(time.RFC3339, strings.Replace(date, " ", "T", 1)+"Z")
return startTime
}
func replaceTimestampInLine(line string, offset string, startTime time.Time) string {
offset, err := getOffset(line)
offsetDuration, _ := time.ParseDuration(offset + "s")
timestamp := startTime.Add(offsetDuration)
if err == nil {
return timestamp.Format("2006-01-02 15:04:05") + ":" + strings.Replace(line, offset, "", 1)
}
return line
}
func reformatTimestamps(log []string) []string {
firstLine := log[0]
startTime := getStartTime(firstLine)
var result []string
for _, line := range log {
line = strings.TrimLeft(line, " \t")
offset, _ := getOffset(line)
result = append(result, replaceTimestampInLine(line, offset, startTime))
}
return result
}