Using Martini middleware, log error if response code is greater than 399

133 views Asked by At

If my server handles a request and writes the response code as being greater than 399, I want to log an error trace:

    bm.Use(func(res http.ResponseWriter, req *http.Request, c martini.Context, log *logging.Logger, statter statsd.Statter) {

        start := time.Now()

        rw := res.(martini.ResponseWriter)

        c.Next()  // do all the middleware handler stuff

        if res.(martini.ResponseWriter).Status() > 399 {
            log.Warning("%v", "print response here")  // how to read response here
        }

})

is there a way to read the response, given the status code? If we send an error back to the client, how can I intercept the error message and log it?

1

There are 1 answers

0
kkkkkkk On

I found c.MapTo on Martini's Readme. If I understand it correctly, this should work:

bm.Use(func(res http.ResponseWriter, req *http.Request, c martini.Context, log *logging.Logger, statter statsd.Statter) {

    var rsp bytes.Buffer

    rw := io.MultiWriter(res, &rsp)

    c.MapTo(rw, (*http.ResponseWriter)(nil))

    c.Next()  // do all the middleware handler stuff

    if res.(martini.ResponseWriter).Status() > 399 {
        log.Warning("%v", rsp.String())
    }

})

Please note that I am not familiar with Martini so I am not sure if this would work.