Pular para o conteúdo

Request Logger

RequestLogger envia valores selecionados da requisição e da resposta para a função obrigatória LogValuesFunc. Use slog ou outra biblioteca. Cada campo Log* ativa a coleta de um valor; por exemplo, LogStatus: true preenche v.Status.

Este programa completo registra a URI e o status em JSON. No repositório do echox, execute cd reference/request-logger && go run . e acesse http://localhost:1323/.

request-logger/main.go
// SPDX-License-Identifier: MIT
// This complete example is the source for the Request Logger documentation.
package main
import (
"log/slog"
"net/http"
"os"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
)
func main() {
e := echo.New()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
HandleError: true,
LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
if v.Error != nil {
logger.Error("request failed", "uri", v.URI, "status", v.Status, "error", v.Error)
return nil
}
logger.Info("request", "uri", v.URI, "status", v.Status)
return nil
},
}))
e.GET("/", func(c *echo.Context) error {
return c.String(http.StatusOK, "hello")
})
if err := e.Start(":1323"); err != nil {
e.Logger.Error("server stopped", "error", err)
}
}

A página importa o mesmo arquivo compilado pela CI da documentação. v.Error recebe o erro retornado pelo próximo handler. Com HandleError: true, o tratador global escreve a resposta antes de executar LogValuesFunc; middlewares anteriores já não podem alterar o status ou o corpo.

Em uma aplicação pequena, LogValuesFunc pode usar fmt.Printf. Ative os campos Log* correspondentes aos valores lidos.

Envie os valores selecionados ao Zerolog dentro de LogValuesFunc.

Use a mesma função para enviar os valores ao Zap.

Monte os campos do Logrus a partir de RequestLoggerValues.

A tabela é gerada dos campos exportados da revisão indicada do Echo. Ela não presume valores padrão em tempo de execução.

RequestLoggerConfig · github.com/labstack/echo/v5@5196b9b

As descrições dos campos são geradas dos comentários do código-fonte em inglês.

Campos do código-fonte
CampoTipoDescriçãoCódigo
Skipper Skipper Skipper defines a function to skip middleware. L126
BeforeNextFunc func(c *echo.Context) BeforeNextFunc defines a function that is called before next middleware or handler is called in chain. L129
LogValuesFunc func(c *echo.Context, v RequestLoggerValues) error LogValuesFunc defines a function that is called with values extracted by logger from request/response. Mandatory. L132
HandleError bool HandleError instructs logger to call global error handler when next middleware/handler returns an error. This is useful when you have custom error handler that can decide to use different status codes. A side-effect of calling global error handler is that now Response has been committed and sent to the client and middlewares up in chain can not change Response status code or response body. L139
LogLatency bool LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call). L142
LogProtocol bool LogProtocol instructs logger to extract request protocol (i.e. `HTTP/1.1` or `HTTP/2`) L144
LogRemoteIP bool LogRemoteIP instructs logger to extract request remote IP. See `echo.Context.RealIP()` for implementation details. L146
LogHost bool LogHost instructs logger to extract request host value (i.e. `example.com`) L148
LogMethod bool LogMethod instructs logger to extract request method value (i.e. `GET` etc) L150
LogURI bool LogURI instructs logger to extract request URI (i.e. `/list?lang=en&page=1`) L152
LogURIPath bool LogURIPath instructs logger to extract request URI path part (i.e. `/list`) L154
LogRoutePath bool LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. `/user/:id`) L156
LogRequestID bool LogRequestID instructs logger to extract request ID from request `X-Request-Id` header or response if request did not have value. L158
LogReferer bool LogReferer instructs logger to extract request referer values. L160
LogUserAgent bool LogUserAgent instructs logger to extract request user agent values. L162
LogStatus bool LogStatus instructs logger to extract response status code. If handler chain returns an error, the status code is extracted from the error satisfying echo.StatusCoder interface. L165
LogContentLength bool LogContentLength instructs logger to extract content length header value. Note: this value could be different from actual request body size as it could be spoofed etc. L168
LogResponseSize bool LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware this value may not be always correct. L171
LogHeaders []string LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than one header with same value so slice of values is been logger for each given header. Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding". L177
LogQueryParams []string LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can contain more than one query parameter with same name so slice of values is been logger for each given query param name. L180
LogFormValues []string LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can contain more than one form value with same name so slice of values is been logger for each given form value name. L183
Funções do código-fonte
TipoCódigo
func RequestLogger() echo.MiddlewareFunc L395
func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc L237

panic: missing LogValuesFunc callback function for request logger middleware

Seção intitulada “panic: missing LogValuesFunc callback function for request logger middleware”

LogValuesFunc é obrigatória. Defina a função antes de chamar RequestLoggerWithConfig; o exemplo executável inclui essa função.

Ative o campo correspondente: LogURI: true para v.URI ou LogStatus: true para v.Status.