refactor: add correlation ID for error response logs

Co-Authored-By: Sindre Rødseth Hansen <sindre.rodseth.hansen@nav.no>
This commit is contained in:
Trong Huu Nguyen
2021-10-04 14:36:41 +02:00
parent ce8d8c6460
commit 788ef1278a
4 changed files with 65 additions and 29 deletions

View File

@@ -2,6 +2,7 @@ package errorhandler
import (
"errors"
"github.com/nais/wonderwall/pkg/middleware/correlationid"
log "github.com/sirupsen/logrus"
"net/http"
)
@@ -11,19 +12,28 @@ var (
InvalidLocaleError = errors.New("InvalidLocale")
)
func respondError(w http.ResponseWriter, statusCode int, cause error) {
log.Error(cause)
func respondError(w http.ResponseWriter, r *http.Request, statusCode int, cause error) {
id, ok := correlationid.GetFromContext(r.Context())
if !ok {
log.Warnf("no correlation id in context")
}
logFields := log.Fields{
"correlation_id": id,
}
log.WithFields(logFields).Error(cause)
w.WriteHeader(statusCode)
}
func InternalError(w http.ResponseWriter, cause error) {
respondError(w, http.StatusInternalServerError, cause)
func InternalError(w http.ResponseWriter, r *http.Request, cause error) {
respondError(w, r, http.StatusInternalServerError, cause)
}
func BadRequest(w http.ResponseWriter, cause error) {
respondError(w, http.StatusBadRequest, cause)
func BadRequest(w http.ResponseWriter, r *http.Request, cause error) {
respondError(w, r, http.StatusBadRequest, cause)
}
func Unauthorized(w http.ResponseWriter, cause error) {
respondError(w, http.StatusUnauthorized, cause)
func Unauthorized(w http.ResponseWriter, r *http.Request, cause error) {
respondError(w, r, http.StatusUnauthorized, cause)
}