Skip to content

Commit

Permalink
fix: workaround to fix the indexing of array of strings not working
Browse files Browse the repository at this point in the history
The bug is in the jsonparser: buger/jsonparser#232

Signed-off-by: Leonardo Di Donato <leodidonato@gmail.com>
  • Loading branch information
leodido committed Jul 19, 2021
1 parent e6587b2 commit 1d12eb9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -137,7 +137,7 @@ Like this:

```caddyfile
log {
format jsonselect "{level} {timestamp:ts} {httpRequest>requestMethod:request>method} {httpRequest>protocol:request>proto} {httpRequest>status:status} {httpRequest>responseSize:size}" {
format jsonselect "{level} {timestamp:ts} {httpRequest>requestMethod:request>method} {httpRequest>protocol:request>proto} {httpRequest>status:status} {httpRequest>responseSize:size} {httpRequest>userAgent:request>headers>User-Agent>[0]}" {
time_format "rfc3339_nano"
}
}
Expand All @@ -146,7 +146,7 @@ log {
Which outputs:

```json
{"level":"info","timestamp":"2021-07-19T14:48:56.262966Z","httpRequest":{"protocol":"HTTP/2.0","requestMethod":"GET","responseSize":17604,"status":200}}
{"level":"info","timestamp":"2021-07-19T14:48:56.262966Z","httpRequest":{"protocol":"HTTP/2.0","requestMethod":"GET","responseSize":17604,"status":200,"userAgent":"Mozilla/5.0 ..."}}
```

## Try it out
Expand Down
34 changes: 16 additions & 18 deletions plugin.go
Expand Up @@ -109,25 +109,23 @@ func (e JSONSelectEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Fie
return buf, err
}

// fixme > indexing array of strings not working at the moment
// fixme > this is a bug in jsonparser (see https://github.com/buger/jsonparser/issues/232)
// todo > workaround by iterating on paths and calling jsonparser.Get()
res := []byte{'{', '}'}
jsonparser.EachKey(
buf.Bytes(),
func(idx int, val []byte, typ jsonparser.ValueType, err error) {
// todo > handle error
switch typ {
case jsonparser.NotExist:
// path not found, skip
case jsonparser.String:
res, _ = jsonparser.Set(res, append(append([]byte{'"'}, val...), '"'), e.setters[idx]...)
default:
res, _ = jsonparser.Set(res, val, e.setters[idx]...)
}
},
e.getters...,
)
// Temporary workaround the bug https://github.com/buger/jsonparser/issues/232
// todo > switch back to EachKey (see git history) for perf reasons when fixed
for idx, paths := range e.getters {
val, typ, _, err := jsonparser.Get(buf.Bytes(), paths...)
if err != nil {
return nil, err
}
switch typ {
case jsonparser.NotExist:
// path not found, skip
case jsonparser.String:
res, _ = jsonparser.Set(res, append(append([]byte{'"'}, val...), '"'), e.setters[idx]...)
default:
res, _ = jsonparser.Set(res, val, e.setters[idx]...)
}
}

// Reset the buffer to output our own content
buf.Reset()
Expand Down

0 comments on commit 1d12eb9

Please sign in to comment.