Skip to content

Commit

Permalink
Support nesting request metrics under a sub dictionary (#14)
Browse files Browse the repository at this point in the history
In some cases you don't want the fields of the request metrics directly
in the root of the dictionary.

For example, when sending general application logs *and* request metric
logs to the same ES index it's good to be able to to nest the request
metrics as a separate object.

This commit adds 1 extra config option `NestKey` holding the name of
a key, that when set will nest the request metric fields in a sub
dictionary under the key name.

Co-authored-by: Taylan Develioglu <[email protected]>
  • Loading branch information
tdevelioglu and Taylan Develioglu authored Dec 9, 2021
1 parent d2c8466 commit 6b6fa8f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ func main() {
}
```

### Nesting under a sub dictionary

```go
e.Use(lecho.Middleware(lecho.Config{
Logger: logger,
NestKey: "request"
}))
// Output: {"level":"info","request":{"remote_ip":"5.6.7.8","method":"GET", ...}, ...}
```

## Helpers

### Level converters
Expand Down
23 changes: 18 additions & 5 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package lecho

import (
"context"
"github.com/rs/zerolog"
"os"
"strconv"
"time"

"github.com/rs/zerolog"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
Expand All @@ -16,6 +17,7 @@ type (
Logger *Logger
Skipper middleware.Skipper
RequestIDKey string
NestKey string
}

Context struct {
Expand Down Expand Up @@ -85,11 +87,18 @@ func Middleware(config Config) echo.MiddlewareFunc {

stop := time.Now()

var evt *zerolog.Event
var mainEvt *zerolog.Event
if err != nil {
evt = logger.log.Err(err)
mainEvt = logger.log.Err(err)
} else {
mainEvt = logger.log.WithLevel(logger.log.GetLevel())
}

var evt *zerolog.Event
if config.NestKey != "" { // Start a new event (dict) if there's a nest key.
evt = zerolog.Dict()
} else {
evt = logger.log.WithLevel(logger.log.GetLevel())
evt = mainEvt
}
evt.Str("remote_ip", c.RealIP())
evt.Str("host", req.Host)
Expand All @@ -108,7 +117,11 @@ func Middleware(config Config) echo.MiddlewareFunc {

evt.Str("bytes_in", cl)
evt.Str("bytes_out", strconv.FormatInt(res.Size, 10))
evt.Send()

if config.NestKey != "" { // Nest the new event (dict) under the nest key.
mainEvt.Dict(config.NestKey, evt)
}
mainEvt.Send()

return err
}
Expand Down

0 comments on commit 6b6fa8f

Please sign in to comment.