mirror of https://github.com/gin-gonic/gin.git
Merge branch 'zaynetro-master' into develop
This commit is contained in:
commit
ec30e4d727
15
logger.go
15
logger.go
|
@ -46,7 +46,17 @@ func Logger() HandlerFunc {
|
||||||
|
|
||||||
// Instance a Logger middleware with the specified writter buffer.
|
// Instance a Logger middleware with the specified writter buffer.
|
||||||
// Example: os.Stdout, a file opened in write mode, a socket...
|
// Example: os.Stdout, a file opened in write mode, a socket...
|
||||||
func LoggerWithWriter(out io.Writer) HandlerFunc {
|
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
|
||||||
|
var skip map[string]struct{}
|
||||||
|
|
||||||
|
if length := len(notlogged); length > 0 {
|
||||||
|
skip = make(map[string]struct{}, length)
|
||||||
|
|
||||||
|
for _, path := range notlogged {
|
||||||
|
skip[path] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return func(c *Context) {
|
return func(c *Context) {
|
||||||
// Start timer
|
// Start timer
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
@ -55,6 +65,8 @@ func LoggerWithWriter(out io.Writer) HandlerFunc {
|
||||||
// Process request
|
// Process request
|
||||||
c.Next()
|
c.Next()
|
||||||
|
|
||||||
|
// Log only when path is not being skipped
|
||||||
|
if _, ok := skip[path]; !ok {
|
||||||
// Stop timer
|
// Stop timer
|
||||||
end := time.Now()
|
end := time.Now()
|
||||||
latency := end.Sub(start)
|
latency := end.Sub(start)
|
||||||
|
@ -77,6 +89,7 @@ func LoggerWithWriter(out io.Writer) HandlerFunc {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func colorForStatus(code int) string {
|
func colorForStatus(code int) string {
|
||||||
switch {
|
switch {
|
||||||
|
|
|
@ -124,3 +124,17 @@ func TestErrorLogger(t *testing.T) {
|
||||||
assert.Equal(t, w.Code, 500)
|
assert.Equal(t, w.Code, 500)
|
||||||
assert.Equal(t, w.Body.String(), "hola!")
|
assert.Equal(t, w.Body.String(), "hola!")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSkippingPaths(t *testing.T) {
|
||||||
|
buffer := new(bytes.Buffer)
|
||||||
|
router := New()
|
||||||
|
router.Use(LoggerWithWriter(buffer, "/skipped"))
|
||||||
|
router.GET("/logged", func(c *Context) {})
|
||||||
|
router.GET("/skipped", func(c *Context) {})
|
||||||
|
|
||||||
|
performRequest(router, "GET", "/logged")
|
||||||
|
assert.Contains(t, buffer.String(), "200")
|
||||||
|
|
||||||
|
performRequest(router, "GET", "/skipped")
|
||||||
|
assert.Contains(t, buffer.String(), "")
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue