Skip to content

Commit 5c7c87d

Browse files
Cyberaxvishr
authored andcommitted
Add ability to set the logger on echo.Context (labstack#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.
1 parent c50c677 commit 5c7c87d

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

context.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,9 @@ type (
183183
// Logger returns the `Logger` instance.
184184
Logger() Logger
185185

186+
// Set the logger
187+
SetLogger(l Logger)
188+
186189
// Echo returns the `Echo` instance.
187190
Echo() *Echo
188191

@@ -202,6 +205,7 @@ type (
202205
handler HandlerFunc
203206
store Map
204207
echo *Echo
208+
logger Logger
205209
lock sync.RWMutex
206210
}
207211
)
@@ -598,9 +602,17 @@ func (c *context) SetHandler(h HandlerFunc) {
598602
}
599603

600604
func (c *context) Logger() Logger {
605+
res := c.logger
606+
if res != nil {
607+
return res
608+
}
601609
return c.echo.Logger
602610
}
603611

612+
func (c *context) SetLogger(l Logger) {
613+
c.logger = l
614+
}
615+
604616
func (c *context) Reset(r *http.Request, w http.ResponseWriter) {
605617
c.request = r
606618
c.response.reset(w)
@@ -609,6 +621,7 @@ func (c *context) Reset(r *http.Request, w http.ResponseWriter) {
609621
c.store = nil
610622
c.path = ""
611623
c.pnames = nil
624+
c.logger = nil
612625
// NOTE: Don't reset because it has to have length c.echo.maxParam at all times
613626
for i := 0; i < *c.echo.maxParam; i++ {
614627
c.pvalues[i] = ""

context_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"encoding/xml"
88
"errors"
99
"fmt"
10+
"github.com/labstack/gommon/log"
1011
"io"
1112
"math"
1213
"mime/multipart"
@@ -800,7 +801,16 @@ func TestContext_Logger(t *testing.T) {
800801
e := New()
801802
c := e.NewContext(nil, nil)
802803

803-
testify.NotNil(t, c.Logger())
804+
log1 := c.Logger()
805+
testify.NotNil(t, log1)
806+
807+
log2 := log.New("echo2")
808+
c.SetLogger(log2)
809+
testify.Equal(t, log2, c.Logger())
810+
811+
// Resetting the context returns the initial logger
812+
c.Reset(nil, nil)
813+
testify.Equal(t, log1, c.Logger())
804814
}
805815

806816
func TestContext_RealIP(t *testing.T) {

0 commit comments

Comments
 (0)