Files

37 lines
1.1 KiB
Go
Raw Permalink Normal View History

2021-07-14 11:14:19 +00:00
package middleware
import (
"net/http"
"time"
2021-08-24 17:48:37 +02:00
"github.com/go-chi/chi/v5/middleware"
2022-05-04 14:49:59 +02:00
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"go.opentelemetry.io/otel/trace"
2021-07-14 11:14:19 +00:00
)
// AccessLog is a middleware to log http requests at info level logging.
func AccessLog(logger log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
2023-07-04 17:08:29 +02:00
requestID := middleware.GetReqID(r.Context())
// add Request Id to all responses
w.Header().Set(middleware.RequestIDHeader, requestID)
2021-07-14 11:14:19 +00:00
wrap := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(wrap, r)
spanContext := trace.SpanContextFromContext(r.Context())
2021-07-14 11:14:19 +00:00
logger.Info().
Str("proto", r.Proto).
2023-07-04 17:08:29 +02:00
Str(log.RequestIDString, requestID).
Str("traceid", spanContext.TraceID().String()).
2021-07-14 11:14:19 +00:00
Str("remote-addr", r.RemoteAddr).
Str("method", r.Method).
Int("status", wrap.Status()).
Str("path", r.URL.Path).
Dur("duration", time.Since(start)).
Int("bytes", wrap.BytesWritten()).
Msg("access-log")
})
}
}