Skip to content

Commit 6b6fa8f

Browse files
tdeveliogluTaylan Develioglu
and
Taylan Develioglu
authored
Support nesting request metrics under a sub dictionary (#14)
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]>
1 parent d2c8466 commit 6b6fa8f

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ func main() {
118118
}
119119
```
120120

121+
### Nesting under a sub dictionary
122+
123+
```go
124+
e.Use(lecho.Middleware(lecho.Config{
125+
Logger: logger,
126+
NestKey: "request"
127+
}))
128+
// Output: {"level":"info","request":{"remote_ip":"5.6.7.8","method":"GET", ...}, ...}
129+
```
130+
121131
## Helpers
122132

123133
### Level converters

middleware.go

+18-5
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ package lecho
22

33
import (
44
"context"
5-
"github.com/rs/zerolog"
65
"os"
76
"strconv"
87
"time"
98

9+
"github.com/rs/zerolog"
10+
1011
"github.com/labstack/echo/v4"
1112
"github.com/labstack/echo/v4/middleware"
1213
)
@@ -16,6 +17,7 @@ type (
1617
Logger *Logger
1718
Skipper middleware.Skipper
1819
RequestIDKey string
20+
NestKey string
1921
}
2022

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

8688
stop := time.Now()
8789

88-
var evt *zerolog.Event
90+
var mainEvt *zerolog.Event
8991
if err != nil {
90-
evt = logger.log.Err(err)
92+
mainEvt = logger.log.Err(err)
93+
} else {
94+
mainEvt = logger.log.WithLevel(logger.log.GetLevel())
95+
}
96+
97+
var evt *zerolog.Event
98+
if config.NestKey != "" { // Start a new event (dict) if there's a nest key.
99+
evt = zerolog.Dict()
91100
} else {
92-
evt = logger.log.WithLevel(logger.log.GetLevel())
101+
evt = mainEvt
93102
}
94103
evt.Str("remote_ip", c.RealIP())
95104
evt.Str("host", req.Host)
@@ -108,7 +117,11 @@ func Middleware(config Config) echo.MiddlewareFunc {
108117

109118
evt.Str("bytes_in", cl)
110119
evt.Str("bytes_out", strconv.FormatInt(res.Size, 10))
111-
evt.Send()
120+
121+
if config.NestKey != "" { // Nest the new event (dict) under the nest key.
122+
mainEvt.Dict(config.NestKey, evt)
123+
}
124+
mainEvt.Send()
112125

113126
return err
114127
}

0 commit comments

Comments
 (0)