Request Logger
RequestLogger は、選択したリクエストとレスポンスの値を必須の LogValuesFunc に渡します。この関数で slog などに記録できます。各 Log* フィールドは対応する値の取得を有効にします。たとえば LogStatus: true を設定すると v.Status に値が入ります。
この完全なプログラムは URI とステータスを JSON で記録します。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 |
トラブルシューティング
Section titled “トラブルシューティング”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 が必要です。