Skip to content

Commit

Permalink
feat: http logger
Browse files Browse the repository at this point in the history
  • Loading branch information
hyeonjungko committed Nov 5, 2023
1 parent 7c0734a commit aac2956
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
44 changes: 44 additions & 0 deletions gapi/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gapi

import (
"context"
"net/http"
"time"

"github.com/rs/zerolog/log"
Expand Down Expand Up @@ -40,3 +41,46 @@ func GrpcLogger(

return result, err
}

type ResponseRecorder struct {
http.ResponseWriter
StatusCode int
Body []byte
}

func (rec *ResponseRecorder) WriteHeader(statusCode int) {
rec.StatusCode = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}

func (rec *ResponseRecorder) Write(body []byte) (int, error) {
rec.Body = body
return rec.ResponseWriter.Write(body)
}

func HttpLogger(
handler http.Handler,
) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
startTime := time.Now()
rec := &ResponseRecorder{
ResponseWriter: res,
StatusCode: http.StatusOK,
}
handler.ServeHTTP(rec, req)
duration := time.Since(startTime)

logger := log.Info()
if rec.StatusCode != http.StatusOK {
logger = log.Error().Bytes("body", rec.Body)
}

logger.Str("protocol", "http").
Str("method", req.Method).
Str("path", req.RequestURI).
Int("status_code", rec.StatusCode).
Str("status_text", http.StatusText(rec.StatusCode)).
Dur("duration", duration).
Msg("received a HTTP request")
})
}
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ func runGatewayServer(config util.Config, store db.Store) {
}

log.Info().Msgf("starting HTTP gateway server at %s", listener.Addr().String())
err = http.Serve(listener, mux)
handler := gapi.HttpLogger(mux)
err = http.Serve(listener, handler)
if err != nil {
log.Fatal().Err(err).Msg("cannot start HTTP gateway server: ")
}
Expand Down

0 comments on commit aac2956

Please sign in to comment.