diff --git a/server/server.go b/server/server.go index 9ef8a95d..29c9d61f 100644 --- a/server/server.go +++ b/server/server.go @@ -15,6 +15,7 @@ import ( "github.com/Layr-Labs/eigenda-proxy/commitments" "github.com/Layr-Labs/eigenda-proxy/metrics" "github.com/Layr-Labs/eigenda-proxy/store" + "github.com/Layr-Labs/eigenda-proxy/utils" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/log" ) @@ -87,6 +88,9 @@ func WithLogging( log log.Logger, ) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { + ctx := utils.ContextWithNewRequestID(r.Context()) + r = r.WithContext(ctx) + log = utils.RequestLogger(ctx, log) log.Info("request", "method", r.Method, "url", r.URL) err := handleFn(w, r) if err != nil { // #nosec G104 @@ -273,17 +277,14 @@ func (svr *Server) WriteResponse(w http.ResponseWriter, data []byte) { } func (svr *Server) WriteInternalError(w http.ResponseWriter, err error) { - svr.log.Error("internal server error", "err", err) w.WriteHeader(http.StatusInternalServerError) } func (svr *Server) WriteNotFound(w http.ResponseWriter, err error) { - svr.log.Info("not found", "err", err) w.WriteHeader(http.StatusNotFound) } func (svr *Server) WriteBadRequest(w http.ResponseWriter, err error) { - svr.log.Info("bad request", "err", err) w.WriteHeader(http.StatusBadRequest) } diff --git a/utils/request_id.go b/utils/request_id.go new file mode 100644 index 00000000..afc7709d --- /dev/null +++ b/utils/request_id.go @@ -0,0 +1,36 @@ +package utils + +import ( + "context" + + "github.com/ethereum/go-ethereum/log" + "github.com/google/uuid" +) + +type ctxKey string + +const ( + // requestIDKey is the context key for the request ID + // used both in the context and in the logger + requestIDKey ctxKey = "requestID" +) + +// getRequestID retrieves the request ID from the context +func getRequestID(ctx context.Context) (string, bool) { + requestID, ok := ctx.Value(requestIDKey).(string) + return requestID, ok +} + +// RequestLogger returns a new logger with the requestID added as a key-value pair +func RequestLogger(ctx context.Context, log log.Logger) log.Logger { + requestID, ok := getRequestID(ctx) + if !ok { + return log + } + return log.With("requestID", requestID) +} + +func ContextWithNewRequestID(ctx context.Context) context.Context { + requestID := uuid.New().String() + return context.WithValue(ctx, requestIDKey, requestID) +}