Skip to content

Commit

Permalink
chore: enable echo logger
Browse files Browse the repository at this point in the history
  • Loading branch information
iagapie committed Nov 27, 2024
1 parent 7626d2d commit bec6cef
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ import (
"net"
"net/http"
"strings"
"unsafe"

"github.com/danielgtaylor/huma/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
"go.uber.org/fx"
"go.uber.org/zap"

"github.com/gowool/echox/api"
)
Expand All @@ -25,6 +28,7 @@ func CtxArea(ctx context.Context) string {
type EchoParams struct {
fx.In
Config RouterConfig
Logger *zap.Logger
ErrorHandler echo.HTTPErrorHandler
Renderer echo.Renderer
Validator echo.Validator
Expand All @@ -41,17 +45,13 @@ func NewEcho(params EchoParams) *echo.Echo {
e.Debug = false
e.HideBanner = true
e.HidePort = true
e.Server.Handler = nil
e.Server = nil
e.TLSServer.Handler = nil
e.TLSServer = nil
e.StdLogger = nil
e.Logger = nil
e.Renderer = params.Renderer
e.Validator = params.Validator
e.IPExtractor = params.IPExtractor
e.Filesystem = params.Filesystem
e.HTTPErrorHandler = params.ErrorHandler
e.StdLogger = zap.NewStdLog(params.Logger)
e.Logger.SetOutput(&loggerWriter{echo: e.Logger, zap: params.Logger})

middlewares := make(map[string]echo.MiddlewareFunc)
for _, middleware := range params.Middlewares {
Expand Down Expand Up @@ -164,3 +164,25 @@ func IPExtractor() echo.IPExtractor {
return ra
}
}

type loggerWriter struct {
echo echo.Logger
zap *zap.Logger
}

func (w *loggerWriter) Write(p []byte) (n int, err error) {
msg := unsafe.String(unsafe.SliceData(p), len(p))

switch w.echo.Level() {
case log.DEBUG:
w.zap.Debug(msg, zap.Any("lvl", w.echo.Level()))
case log.INFO:
w.zap.Info(msg, zap.Any("lvl", w.echo.Level()))
case log.WARN:
w.zap.Warn(msg, zap.Any("lvl", w.echo.Level()))
case log.OFF:
default:
w.zap.Error(msg, zap.Any("lvl", w.echo.Level()))
}
return len(p), nil
}

0 comments on commit bec6cef

Please sign in to comment.