1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-01 00:55:04 +02:00

Atomically write logs in the Logger middleware

This commit is contained in:
zjx20
2016-04-22 19:05:49 +08:00
parent c830734fd5
commit 496ea19a80

View File

@ -1,11 +1,13 @@
package middleware package middleware
import ( import (
"bytes"
"fmt" "fmt"
"io" "io"
"net" "net"
"os" "os"
"strconv" "strconv"
"sync"
"time" "time"
"github.com/labstack/echo" "github.com/labstack/echo"
@ -39,6 +41,7 @@ type (
template *fasttemplate.Template template *fasttemplate.Template
color *color.Color color *color.Color
bufferPool sync.Pool
} }
) )
@ -73,6 +76,11 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
if w, ok := config.Output.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { if w, ok := config.Output.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) {
config.color.Disable() config.color.Disable()
} }
config.bufferPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 256))
},
}
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) { return func(c echo.Context) (err error) {
@ -84,7 +92,11 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
} }
stop := time.Now() stop := time.Now()
_, err = config.template.ExecuteFunc(config.Output, func(w io.Writer, tag string) (int, error) { buffer := config.bufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer config.bufferPool.Put(buffer)
_, err = config.template.ExecuteFunc(buffer, func(w io.Writer, tag string) (int, error) {
switch tag { switch tag {
case "time_rfc3339": case "time_rfc3339":
return w.Write([]byte(time.Now().Format(time.RFC3339))) return w.Write([]byte(time.Now().Format(time.RFC3339)))
@ -128,6 +140,9 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
return w.Write([]byte(fmt.Sprintf("[unknown tag %s]", tag))) return w.Write([]byte(fmt.Sprintf("[unknown tag %s]", tag)))
} }
}) })
if err == nil {
config.Output.Write(buffer.Bytes())
}
return return
} }
} }