58 lines
1 KiB
Go
58 lines
1 KiB
Go
package parser
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
"watch-tool/models"
|
|
)
|
|
|
|
type RegexLogParser struct {
|
|
Pattern *regexp.Regexp
|
|
Fields map[string]string
|
|
Toolname string
|
|
Hostname string
|
|
}
|
|
|
|
func (p *RegexLogParser) Parse(line string) (models.LogMessage, error) {
|
|
entry := models.LogMessage{Type: "log_entry"}
|
|
entry.Tool = p.Toolname
|
|
entry.Raw = line
|
|
entry.Host = p.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
|
|
}
|