Request Logger
RequestLogger entrega los valores seleccionados de la petición y la respuesta a la función obligatoria LogValuesFunc. Puedes usar slog u otra biblioteca. Cada campo Log* activa la extracción de un valor; por ejemplo, LogStatus: true rellena v.Status.
Ejemplos
Sección titulada «Ejemplos»Este programa completo registra la URI y el estado como JSON. Desde el repositorio de echox, ejecuta cd reference/request-logger && go run . y solicita http://localhost:1323/.
// 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) }}La página importa el mismo archivo que compila la CI de documentación. v.Error recibe el error devuelto por el siguiente handler. Con HandleError: true, el manejador global escribe la respuesta antes de ejecutar LogValuesFunc; los middleware anteriores ya no pueden cambiar el estado ni el cuerpo.
fmt.Printf
Sección titulada «fmt.Printf»En una aplicación pequeña, LogValuesFunc puede usar fmt.Printf. Activa los campos Log* de los valores que quieras leer.
Pasa los valores seleccionados a Zerolog dentro de LogValuesFunc.
Usa la misma función para enviar los valores a Zap.
Crea los campos de Logrus a partir de RequestLoggerValues.
Configuración
Sección titulada «Configuración»La tabla se genera a partir de los campos exportados de la revisión indicada de Echo. No presupone valores predeterminados en tiempo de ejecución.
RequestLoggerConfig · github.com/labstack/echo/v5@5196b9b
Las descripciones de los campos se generan a partir de comentarios del código fuente en inglés.
| Campo | Tipo | Descripción | Fuente |
|---|---|---|---|
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 |
Solución de problemas
Sección titulada «Solución de problemas»panic: missing LogValuesFunc callback function for request logger middleware
Sección titulada «panic: missing LogValuesFunc callback function for request logger middleware»LogValuesFunc es obligatoria. Asígnala antes de llamar a RequestLoggerWithConfig; el ejemplo ejecutable incluye esta función.
Los parámetros en los logs están vacíos
Sección titulada «Los parámetros en los logs están vacíos»Activa el campo de extracción correspondiente: LogURI: true para v.URI o LogStatus: true para v.Status.