parser.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package liquidsoap
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "regexp"
  8. "strconv"
  9. )
  10. // Output represents a liquidsoap message in a structured form
  11. type Output struct {
  12. Level int // lower means more important
  13. Msg string
  14. Component string
  15. }
  16. // Parse needs a reader of the log, and will produce parsed output
  17. func Parse(r io.Reader, parsed chan<- Output) {
  18. scanner := bufio.NewScanner(r)
  19. for scanner.Scan() {
  20. out, err := outParseLine(scanner.Text())
  21. if err == nil {
  22. parsed <- out
  23. }
  24. }
  25. }
  26. var lineRegex = regexp.MustCompile(`^([0-9]{4}/[0-9]{2}/[0-9]{2}) ([0-9:]{8}) \[([^:\[\]]*):([0-9])\] (.*)$`)
  27. func outParseLine(line string) (Output, error) {
  28. res := lineRegex.FindStringSubmatch(line)
  29. if res == nil {
  30. return Output{}, errors.New("Invalid line")
  31. }
  32. if len(res) != 6 {
  33. return Output{}, errors.New("Invalid line: missing parts")
  34. }
  35. level, err := strconv.Atoi(res[4])
  36. if err != nil {
  37. return Output{}, fmt.Errorf("Invalid line: invalid level `%s`", res[4])
  38. }
  39. return Output{Level: level, Msg: res[5], Component: res[3]}, nil
  40. }