ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration.
()
| 244 | |
| 245 | // ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration. |
| 246 | func (config RequestLoggerConfig) ToMiddleware() (echo.MiddlewareFunc, error) { |
| 247 | if config.Skipper == nil { |
| 248 | config.Skipper = DefaultSkipper |
| 249 | } |
| 250 | now := time.Now |
| 251 | if config.timeNow != nil { |
| 252 | now = config.timeNow |
| 253 | } |
| 254 | |
| 255 | if config.LogValuesFunc == nil { |
| 256 | return nil, errors.New("missing LogValuesFunc callback function for request logger middleware") |
| 257 | } |
| 258 | |
| 259 | logHeaders := len(config.LogHeaders) > 0 |
| 260 | headers := append([]string(nil), config.LogHeaders...) |
| 261 | for i, v := range headers { |
| 262 | headers[i] = http.CanonicalHeaderKey(v) |
| 263 | } |
| 264 | |
| 265 | logQueryParams := len(config.LogQueryParams) > 0 |
| 266 | logFormValues := len(config.LogFormValues) > 0 |
| 267 | |
| 268 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 269 | return func(c *echo.Context) error { |
| 270 | if config.Skipper(c) { |
| 271 | return next(c) |
| 272 | } |
| 273 | |
| 274 | req := c.Request() |
| 275 | start := now() |
| 276 | |
| 277 | if config.BeforeNextFunc != nil { |
| 278 | config.BeforeNextFunc(c) |
| 279 | } |
| 280 | err := next(c) |
| 281 | if err != nil && config.HandleError { |
| 282 | // When global error handler writes the error to the client the Response gets "committed". This state can be |
| 283 | // checked with `c.Response().Committed` field. |
| 284 | c.Echo().HTTPErrorHandler(c, err) |
| 285 | } |
| 286 | res := c.Response() |
| 287 | |
| 288 | v := RequestLoggerValues{ |
| 289 | StartTime: start, |
| 290 | } |
| 291 | if config.LogLatency { |
| 292 | v.Latency = now().Sub(start) |
| 293 | } |
| 294 | if config.LogProtocol { |
| 295 | v.Protocol = req.Proto |
| 296 | } |
| 297 | if config.LogRemoteIP { |
| 298 | v.RemoteIP = c.RealIP() |
| 299 | } |
| 300 | if config.LogHost { |
| 301 | v.Host = req.Host |
| 302 | } |
| 303 | if config.LogMethod { |