This commit is contained in:
Aliaksandr Valialkin 2024-05-30 19:56:50 +02:00
parent 68b3bd370e
commit 82f186c6bc
No known key found for this signature in database
GPG key ID: 52C003EE2BCDB9EB
3 changed files with 19 additions and 18 deletions

View file

@ -15,6 +15,10 @@ func (p *logfmtParser) reset() {
} }
func (p *logfmtParser) addField(name, value string) { func (p *logfmtParser) addField(name, value string) {
name = strings.TrimSpace(name)
if name == "" && value == "" {
return
}
p.fields = append(p.fields, Field{ p.fields = append(p.fields, Field{
Name: name, Name: name,
Value: value, Value: value,
@ -24,14 +28,21 @@ func (p *logfmtParser) addField(name, value string) {
func (p *logfmtParser) parse(s string) { func (p *logfmtParser) parse(s string) {
for { for {
// Search for field name // Search for field name
n := strings.IndexByte(s, '=') n := strings.IndexAny(s, "= ")
if n < 0 { if n < 0 {
// field name couldn't be read // empty value
p.addField(s, "")
return return
} }
name := strings.TrimSpace(s[:n]) name := s[:n]
ch := s[n]
s = s[n+1:] s = s[n+1:]
if ch == ' ' {
// empty value
p.addField(name, "")
continue
}
if len(s) == 0 { if len(s) == 0 {
p.addField(name, "") p.addField(name, "")
return return

View file

@ -22,9 +22,9 @@ func TestLogfmtParser(t *testing.T) {
f(`foo=bar`, `{"foo":"bar"}`) f(`foo=bar`, `{"foo":"bar"}`)
f(`foo="bar=baz x=y"`, `{"foo":"bar=baz x=y"}`) f(`foo="bar=baz x=y"`, `{"foo":"bar=baz x=y"}`)
f(`foo=`, `{"foo":""}`) f(`foo=`, `{"foo":""}`)
f(`foo`, `{"foo":""}`)
f(`foo bar`, `{"foo":"","bar":""}`)
f(`foo bar=baz`, `{"foo":"","bar":"baz"}`)
f(`foo=bar baz="x y" a=b`, `{"foo":"bar","baz":"x y","a":"b"}`) f(`foo=bar baz="x y" a=b`, `{"foo":"bar","baz":"x y","a":"b"}`)
f(` foo=bar baz=x =z qwe`, `{"foo":"bar","baz":"x","":"z","qwe":""}`)
// errors
f(`foo`, `{}`)
f(`foo=bar baz=x z qwe`, `{"foo":"bar","baz":"x"}`)
} }

View file

@ -191,17 +191,6 @@ func TestPipeUnpackLogfmt(t *testing.T) {
}, },
}) })
// single row, unpack from non-json field
f("unpack_logfmt from x", [][]Field{
{
{"x", `foobar`},
},
}, [][]Field{
{
{"x", `foobar`},
},
})
// single row, unpack from non-logfmt // single row, unpack from non-logfmt
f("unpack_logfmt from x", [][]Field{ f("unpack_logfmt from x", [][]Field{
{ {
@ -210,6 +199,7 @@ func TestPipeUnpackLogfmt(t *testing.T) {
}, [][]Field{ }, [][]Field{
{ {
{"x", `foobar`}, {"x", `foobar`},
{"foobar", ""},
}, },
}) })