refactor: use parser package for file monitor
This commit is contained in:
parent
e468b3a0e3
commit
72b6ad88c7
2 changed files with 81 additions and 133 deletions
64
parser/regex_parser.go
Normal file
64
parser/regex_parser.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package parser
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
"tixel_watch/helpers"
|
||||
"tixel_watch/models"
|
||||
)
|
||||
|
||||
type RegexLogParser struct {
|
||||
Pattern *regexp.Regexp
|
||||
Fields map[string]string
|
||||
Toolname string
|
||||
}
|
||||
|
||||
func (p *RegexLogParser) Parse(line string) (models.LogMessage, error) {
|
||||
entry := models.LogMessage{Type: "log_entry"}
|
||||
entry.Tool = p.Toolname
|
||||
entry.Raw = line
|
||||
hostname, err := helpers.GetHostname()
|
||||
if err != nil {
|
||||
slog.Warn("cannot get hostname")
|
||||
return entry, err
|
||||
}
|
||||
entry.Host = hostname
|
||||
|
||||
fields := p.parseWithPattern(line)
|
||||
if fields != nil {
|
||||
entry.Fields = fields
|
||||
} else {
|
||||
entry.LogMessage = strings.TrimSpace(line)
|
||||
}
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func (p *RegexLogParser) parseWithPattern(text string) map[string]any {
|
||||
matches := p.Pattern.FindStringSubmatch(text)
|
||||
if matches == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
fields := make(map[string]any)
|
||||
subexpNames := p.Pattern.SubexpNames()
|
||||
|
||||
for i, match := range matches {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if i < len(subexpNames) && subexpNames[i] != "" {
|
||||
fieldName := subexpNames[i]
|
||||
|
||||
if mappedName, exists := p.Fields[fieldName]; exists {
|
||||
fieldName = mappedName
|
||||
}
|
||||
|
||||
fields[fieldName] = match
|
||||
}
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue