Created
November 29, 2018 14:57
-
-
Save mozey/aca264f9c03e6fdd977a7d9e0ac86cbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/labstack/echo/middleware" | |
"net/http" | |
"github.com/labstack/echo" | |
) | |
// Skipper determines which requests to log | |
func Skipper(c echo.Context) bool { | |
res := c.Response() | |
status := res.Status | |
fmt.Println("Skipper status: ", status) | |
// Skips request logging if not success status, | |
// those are logged by customHTTPErrorHandler | |
if status > 299 { | |
return true | |
} | |
return false | |
} | |
func customHTTPErrorHandler(err error, c echo.Context) { | |
res := c.Response() | |
status := res.Status | |
fmt.Println("customHTTPErrorHandler status", status) | |
// Parse error | |
code := http.StatusInternalServerError | |
message := http.StatusText(http.StatusInternalServerError) | |
if he, ok := err.(*echo.HTTPError); ok { | |
code = he.Code | |
message = fmt.Sprintf("%s", he.Message) | |
} | |
type response struct { | |
Message string `json:"message"` | |
} | |
resp := response{ | |
Message: message, | |
} | |
// Respond with error | |
if err := c.JSON(code, resp); err != nil { | |
c.Logger().Error(err) | |
} | |
// Log error | |
c.Logger().Error(err) | |
} | |
func main() { | |
// Echo instance | |
e := echo.New() | |
// Middleware | |
loggerConfig := middleware.DefaultLoggerConfig | |
loggerConfig.Skipper = Skipper | |
loggerConfig.Format = `{"status":${status},"error":"${error}"}` | |
e.Use(middleware.LoggerWithConfig(loggerConfig)) | |
e.HTTPErrorHandler = customHTTPErrorHandler | |
// Routes | |
e.GET("/", hello) | |
// Start server | |
e.Logger.Fatal(e.Start(":1323")) | |
} | |
// Handler | |
func hello(c echo.Context) error { | |
fmt.Println("hello") | |
return echo.NewHTTPError(http.StatusInternalServerError) | |
} | |
// This file demonstrates that the logger skipper cannot be used | |
// to check HTTP status unless it is called after the inner middleware... | |
// BEFORE | |
//Skipper status: 200 | |
//hello | |
//customHTTPErrorHandler status 200 | |
//{"time":"2018-11-29T16:52:14.472436+02:00","level":"ERROR","prefix":"echo","file":"main.go","line":"51","message":"code=500, message=Internal Server Error"} | |
//{"status":500,"error":"code=500, message=Internal Server Error"} | |
// AFTER | |
//hello | |
//customHTTPErrorHandler status 200 | |
//{"time":"2018-11-29T16:53:12.321411+02:00","level":"ERROR","prefix":"echo","file":"main.go","line":"51","message":"code=500, message=Internal Server Error"} | |
//Skipper status: 500 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment