This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Increase logging verbosity for error responses
- Loading branch information
B&R
committed
Mar 20, 2023
1 parent
767707a
commit b0f0600
Showing
2 changed files
with
42 additions
and
3 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package http | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"github.com/gin-gonic/gin" | ||
"github.com/sirupsen/logrus" | ||
"strings" | ||
) | ||
|
||
type errorLogWriter struct { | ||
gin.ResponseWriter | ||
body *bytes.Buffer | ||
} | ||
|
||
func (w errorLogWriter) Write(b []byte) (int, error) { | ||
if w.Status() > 299 && strings.Contains(w.Header().Get("Content-Type"), "application/json") { | ||
w.body.Write(b) | ||
} | ||
return w.ResponseWriter.Write(b) | ||
} | ||
|
||
func responseErrorLoggerMiddleware() gin.HandlerFunc { | ||
return func(c *gin.Context) { | ||
blw := &errorLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} | ||
c.Writer = blw | ||
c.Next() | ||
if len(blw.body.String()) > 0 { | ||
response := GenericResponseType{} | ||
unmarshalErr := json.Unmarshal(blw.body.Bytes(), &response) | ||
if unmarshalErr != nil { | ||
logrus.Warningln("Cannot parse error response. Probably not in valid format") | ||
return | ||
} | ||
logrus.Errorf("Returned '%s' error, message: '%s'", response.Error, response.Message) | ||
} | ||
} | ||
} |
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