From 5c7c87d09e23a8943f71f3057030919fb28f1349 Mon Sep 17 00:00:00 2001 From: Alex Besogonov Date: Mon, 11 Nov 2019 12:34:13 -0800 Subject: [PATCH] Add ability to set the logger on echo.Context (#1377) This change allows middleware to replace the logger on the echo.Context with a customized per-request logger with additional fields. The logger is reset to default on every Reset() call. --- context.go | 13 +++++++++++++ context_test.go | 12 +++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 91e7c046..27da5ffe 100644 --- a/context.go +++ b/context.go @@ -183,6 +183,9 @@ type ( // Logger returns the `Logger` instance. Logger() Logger + // Set the logger + SetLogger(l Logger) + // Echo returns the `Echo` instance. Echo() *Echo @@ -202,6 +205,7 @@ type ( handler HandlerFunc store Map echo *Echo + logger Logger lock sync.RWMutex } ) @@ -598,9 +602,17 @@ func (c *context) SetHandler(h HandlerFunc) { } func (c *context) Logger() Logger { + res := c.logger + if res != nil { + return res + } return c.echo.Logger } +func (c *context) SetLogger(l Logger) { + c.logger = l +} + func (c *context) Reset(r *http.Request, w http.ResponseWriter) { c.request = r c.response.reset(w) @@ -609,6 +621,7 @@ func (c *context) Reset(r *http.Request, w http.ResponseWriter) { c.store = nil c.path = "" c.pnames = nil + c.logger = nil // NOTE: Don't reset because it has to have length c.echo.maxParam at all times for i := 0; i < *c.echo.maxParam; i++ { c.pvalues[i] = "" diff --git a/context_test.go b/context_test.go index d85a17e8..47be19cc 100644 --- a/context_test.go +++ b/context_test.go @@ -7,6 +7,7 @@ import ( "encoding/xml" "errors" "fmt" + "github.com/labstack/gommon/log" "io" "math" "mime/multipart" @@ -800,7 +801,16 @@ func TestContext_Logger(t *testing.T) { e := New() c := e.NewContext(nil, nil) - testify.NotNil(t, c.Logger()) + log1 := c.Logger() + testify.NotNil(t, log1) + + log2 := log.New("echo2") + c.SetLogger(log2) + testify.Equal(t, log2, c.Logger()) + + // Resetting the context returns the initial logger + c.Reset(nil, nil) + testify.Equal(t, log1, c.Logger()) } func TestContext_RealIP(t *testing.T) {