Skip to content

Instantly share code, notes, and snippets.

@nilesh-akhade
Created January 5, 2023 12:47
Show Gist options
  • Save nilesh-akhade/0b4c6fd82241f90d2f499726b76a83b1 to your computer and use it in GitHub Desktop.
Save nilesh-akhade/0b4c6fd82241f90d2f499726b76a83b1 to your computer and use it in GitHub Desktop.
Unmarshal logs marshaled by `logrus.TextFormatter`
package main
import (
"encoding/json"
"fmt"
"regexp"
)
func main() {
s := `time="2022-12-29T14:42:24Z" level=info msg="starting \"n=ew\" restore" logSource='pkg/co=ntroller/restore_controller.go:478' restore=velero/test-13`
m := parse(s)
p, _ := json.Marshal(m)
fmt.Printf("%s\n", p)
fmt.Printf("message=%s\n", m["msg"])
}
func parse(s string) map[string]string {
reKV := regexp.MustCompile(`(?P<key>\w+)=["'](?P<value>(?:[^"'])+)["']|(?P<key2>\w+)=(?P<value2>\w+)`)
re := regexp.MustCompile(`time="(?P<time>.*)" level=(?P<level>\w+) msg=(?P<msg>".*") logSource='(?P<logSource>.*)' (?P<extra>.*)`)
matches := re.FindAllStringSubmatch(s, -1)
output := map[string]string{}
for _, match := range matches {
time := match[1]
level := match[2]
strMsg := ""
json.Unmarshal([]byte(match[3]), &strMsg)
logSource := match[4]
output["time"] = time
output["level"] = level
output["msg"] = strMsg
output["logSource"] = logSource
extra := match[5]
extraMatches := reKV.FindAllStringSubmatch(extra, -1)
for _, m := range extraMatches {
if len(m[1]) == 0 {
output[m[3]] = m[4]
} else {
output[m[1]] = m[2]
}
}
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment