diff --git a/src/api/handlers.go b/src/api/handlers.go index 70d543d1..da492af7 100644 --- a/src/api/handlers.go +++ b/src/api/handlers.go @@ -13,12 +13,10 @@ import ( "strconv" "sync" "time" - "github.com/OpenFactorioServerManager/factorio-server-manager/bootstrap" "github.com/OpenFactorioServerManager/factorio-server-manager/factorio" + "github.com/gorilla/mux" "github.com/gorilla/sessions" - - "github.com/gorilla/mux" ) const readHttpBodyError = "Could not read the Request Body." @@ -247,7 +245,7 @@ func LogTail(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json;charset=UTF-8") config := bootstrap.GetConfig() - resp, err = factorio.TailLog() + resp, err = factorio.TailLog(config.FactorioLog) if err != nil { resp = fmt.Sprintf("Could not tail %s: %s", config.FactorioLog, err) return diff --git a/src/factorio/gamelog.go b/src/factorio/gamelog.go index e920301e..8f793620 100644 --- a/src/factorio/gamelog.go +++ b/src/factorio/gamelog.go @@ -1,14 +1,19 @@ package factorio import ( + "errors" "log" + "regexp" + "strings" + "time" - "github.com/OpenFactorioServerManager/factorio-server-manager/bootstrap" "github.com/hpcloud/tail" + "github.com/OpenFactorioServerManager/factorio-server-manager/bootstrap" ) -func TailLog() ([]string, error) { - result := []string{} +// TailLog tails the Factorio game log file +func TailLog(filename string) ([]string, error) { + var result []string config := bootstrap.GetConfig() @@ -22,5 +27,54 @@ func TailLog() ([]string, error) { 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 +}