Skip to content

RequestLogger middleware can log wrong status codes #2015

Description

@stevenvegt

Issue Description

The RequestLogger has 2 problems:

  1. If a handler returns another error than a echo.HTTPError the status logged is alway 200. This is because of these lines

    if config.LogStatus {
    v.Status = res.Status
    if err != nil {
    if httpErr, ok := err.(*echo.HTTPError); ok {
    v.Status = httpErr.Code
    }
    }
    }
    .

  2. The RequestLogger is middleware, so If the error handler (or another middleware) writes a different status code (after the logger middleware), the logged status code is wrong.

Working code to debug

Code to reproduce 1

func main() {
	e := echo.New()
	e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
		LogStatus: true,
		LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
			fmt.Println(values.Status)
			return nil
		},
	}))

	e.GET("/fail", func(context echo.Context) error {
		return errors.New("failed")
	})
	e.Start(":1323")
}

GET http://localhost:1323/fail -> 500
Prints 200

Code to reproduce 2:

e := echo.New()

	e.HTTPErrorHandler = func(err error, context echo.Context) {
		context.NoContent(404)
	}

	e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
		LogURI:    true,
		LogStatus: true,
		LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
			fmt.Println(values.Status)
			return nil
		},
	}))

	e.GET("/fail", func(context echo.Context) error {
		return echo.NewHTTPError(400, "failed")
	})
	e.Start(":1323")

GET http://localhost:1323/fail -> 404
Prints 400

Version

Version 4.6.1

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions