Request Logger
RequestLogger 将选定的请求和响应数据传给必填的 LogValuesFunc 回调。你可以在回调中使用 slog 或其他日志库。每个 Log* 字段控制对应数据的提取;例如,LogStatus: true 会填充 v.Status。
下面的完整程序以 JSON 格式记录 URI 和状态码。在 echox 源码目录运行 cd reference/request-logger && go run .,然后访问 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) }}本页直接导入文档 CI 编译的同一个文件。下一个处理器返回错误时,v.Error 会包含该错误。设置 HandleError: true 后,全局错误处理器会先写入响应,再调用 LogValuesFunc;上游中间件此时无法更改状态码或响应体。
fmt.Printf
Section titled “fmt.Printf”在小型应用中,LogValuesFunc 可以调用 fmt.Printf。记得启用所读取数据对应的 Log* 字段。
在 LogValuesFunc 中将选定的数据传给 Zerolog。
同一个回调也可以将数据传给 Zap。
从 RequestLoggerValues 构造 Logrus 字段。
下表由所标注 Echo 修订版本的导出字段生成,不推断运行时默认值。
RequestLoggerConfig · github.com/labstack/echo/v5@5196b9b
字段说明由英文源码注释生成。
| 字段 | 类型 | 说明 | 源码 |
|---|---|---|---|
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 |
panic: missing LogValuesFunc callback function for request logger middleware
Section titled “panic: missing LogValuesFunc callback function for request logger middleware”LogValuesFunc 为必填项。调用 RequestLoggerWithConfig 前需设置它;上面的可运行示例已包含该回调。
日志中的参数为空
Section titled “日志中的参数为空”启用对应的提取字段:v.URI 需要 LogURI: true,v.Status 需要 LogStatus: true。