From 6b6fa8f28aa60399a4fa98bf9c1ebdd2077ade46 Mon Sep 17 00:00:00 2001 From: tdevelioglu Date: Thu, 9 Dec 2021 21:03:20 +0100 Subject: [PATCH] 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 --- README.md | 10 ++++++++++ middleware.go | 23 ++++++++++++++++++----- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 247339c..57dfe8d 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/middleware.go b/middleware.go index e5655c4..959d1ed 100644 --- a/middleware.go +++ b/middleware.go @@ -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" ) @@ -16,6 +17,7 @@ type ( Logger *Logger Skipper middleware.Skipper RequestIDKey string + NestKey string } Context struct { @@ -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) @@ -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 }