Skip to content

Commit

Permalink
handler: Pass request context to logger when logging (#1237)
Browse files Browse the repository at this point in the history
* chore: Pass request context to logger when logging

This allows the logger passed to the tusd handler to access the request
specific context and pull out things like sentry information or trace
information. Implements #1236

* chore: bump exp and update log to use Context
  • Loading branch information
mmhand123 authored Jan 14, 2025
1 parent 3cb8a70 commit d69efe0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 17 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ require (
github.com/stretchr/testify v1.10.0
github.com/tus/lockfile v1.2.0
github.com/vimeo/go-util v1.4.1
golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8
golang.org/x/net v0.33.0
golang.org/x/sync v0.10.0
google.golang.org/api v0.214.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,8 @@ golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ss
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME=
golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA=
golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
Expand Down
32 changes: 16 additions & 16 deletions pkg/handler/unrouted_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,10 @@ func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler {
// We also update the write deadline, but makes sure that it is larger than the read deadline, so we
// can still write a response in the case of a read timeout.
if err := c.resC.SetReadDeadline(time.Now().Add(handler.config.NetworkTimeout)); err != nil {
c.log.Warn("NetworkControlError", "error", err)
c.log.WarnContext(c, "NetworkControlError", "error", err)
}
if err := c.resC.SetWriteDeadline(time.Now().Add(2 * handler.config.NetworkTimeout)); err != nil {
c.log.Warn("NetworkControlError", "error", err)
c.log.WarnContext(c, "NetworkControlError", "error", err)
}

// Allow overriding the HTTP method. The reason for this is
Expand All @@ -190,7 +190,7 @@ func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler {
r.Method = newMethod
}

c.log.Info("RequestIncoming")
c.log.InfoContext(c, "RequestIncoming")

handler.Metrics.incRequestsTotal(r.Method)

Expand Down Expand Up @@ -405,7 +405,7 @@ func (handler *UnroutedHandler) PostFile(w http.ResponseWriter, r *http.Request)

handler.Metrics.incUploadsCreated()
c.log = c.log.With("id", id)
c.log.Info("UploadCreated", "size", size, "url", url)
c.log.InfoContext(c, "UploadCreated", "size", size, "url", url)

if handler.config.NotifyCreatedUploads {
handler.CreatedUploads <- newHookEvent(c, info)
Expand Down Expand Up @@ -572,7 +572,7 @@ func (handler *UnroutedHandler) PostFileV2(w http.ResponseWriter, r *http.Reques

handler.Metrics.incUploadsCreated()
c.log = c.log.With("id", id)
c.log.Info("UploadCreated", "size", info.Size, "url", url)
c.log.InfoContext(c, "UploadCreated", "size", info.Size, "url", url)

if handler.config.NotifyCreatedUploads {
handler.CreatedUploads <- newHookEvent(c, info)
Expand Down Expand Up @@ -891,7 +891,7 @@ func (handler *UnroutedHandler) writeChunk(c *httpContext, resp HTTPResponse, up
maxSize = length
}

c.log.Info("ChunkWriteStart", "maxSize", maxSize, "offset", offset)
c.log.InfoContext(c, "ChunkWriteStart", "maxSize", maxSize, "offset", offset)

var bytesWritten int64
var err error
Expand All @@ -907,12 +907,12 @@ func (handler *UnroutedHandler) writeChunk(c *httpContext, resp HTTPResponse, up
// Update the read deadline for every successful read operation. This ensures that the request handler
// keeps going while data is transmitted but that dead connections can also time out and be cleaned up.
if err := c.resC.SetReadDeadline(time.Now().Add(handler.config.NetworkTimeout)); err != nil {
c.log.Warn("NetworkTimeoutError", "error", err)
c.log.WarnContext(c, "NetworkTimeoutError", "error", err)
}

// The write deadline is updated accordingly to ensure that we can also write responses.
if err := c.resC.SetWriteDeadline(time.Now().Add(2 * handler.config.NetworkTimeout)); err != nil {
c.log.Warn("NetworkTimeoutError", "error", err)
c.log.WarnContext(c, "NetworkTimeoutError", "error", err)
}
}

Expand All @@ -935,7 +935,7 @@ func (handler *UnroutedHandler) writeChunk(c *httpContext, resp HTTPResponse, up
// it in the response, if the store did not also return an error.
bodyErr := c.body.hasError()
if bodyErr != nil {
c.log.Error("BodyReadError", "error", bodyErr.Error())
c.log.ErrorContext(c, "BodyReadError", "error", bodyErr.Error())
if err == nil {
err = bodyErr
}
Expand All @@ -947,12 +947,12 @@ func (handler *UnroutedHandler) writeChunk(c *httpContext, resp HTTPResponse, up
if terminateErr := handler.terminateUpload(c, upload, info); terminateErr != nil {
// We only log this error and not show it to the user since this
// termination error is not relevant to the uploading client
c.log.Error("UploadStopTerminateError", "error", terminateErr.Error())
c.log.ErrorContext(c, "UploadStopTerminateError", "error", terminateErr.Error())
}
}
}

c.log.Info("ChunkWriteComplete", "bytesWritten", bytesWritten)
c.log.InfoContext(c, "ChunkWriteComplete", "bytesWritten", bytesWritten)

// Send new offset to client
newOffset := offset + bytesWritten
Expand Down Expand Up @@ -1003,7 +1003,7 @@ func (handler *UnroutedHandler) emitFinishEvents(c *httpContext, resp HTTPRespon
resp = resp.MergeWith(resp2)
}

c.log.Info("UploadFinished", "size", info.Size)
c.log.InfoContext(c, "UploadFinished", "size", info.Size)
handler.Metrics.incUploadsFinished()

if handler.config.NotifyCompleteUploads {
Expand Down Expand Up @@ -1239,7 +1239,7 @@ func (handler *UnroutedHandler) terminateUpload(c *httpContext, upload Upload, i
handler.TerminatedUploads <- newHookEvent(c, info)
}

c.log.Info("UploadTerminated")
c.log.InfoContext(c, "UploadTerminated")
handler.Metrics.incUploadsTerminated()

return nil
Expand All @@ -1253,7 +1253,7 @@ func (handler *UnroutedHandler) sendError(c *httpContext, err error) {
var detailedErr Error

if !errors.As(err, &detailedErr) {
c.log.Error("InternalServerError", "message", err.Error())
c.log.ErrorContext(c, "InternalServerError", "message", err.Error())
detailedErr = NewError("ERR_INTERNAL_SERVER_ERROR", err.Error(), http.StatusInternalServerError)
}

Expand All @@ -1271,7 +1271,7 @@ func (handler *UnroutedHandler) sendError(c *httpContext, err error) {
func (handler *UnroutedHandler) sendResp(c *httpContext, resp HTTPResponse) {
resp.writeTo(c.res)

c.log.Info("ResponseOutgoing", "status", resp.StatusCode, "body", resp.Body)
c.log.InfoContext(c, "ResponseOutgoing", "status", resp.StatusCode, "body", resp.Body)
}

// Make an absolute URLs to the given upload id. If the base path is absolute
Expand Down Expand Up @@ -1432,7 +1432,7 @@ func (handler *UnroutedHandler) lockUpload(c *httpContext, id string) (Lock, err

// No need to wrap this in a sync.OnceFunc because c.cancel will be a noop after the first call.
releaseLock := func() {
c.log.Info("UploadInterrupted")
c.log.InfoContext(c, "UploadInterrupted")
c.cancel(ErrUploadInterrupted)
}

Expand Down

0 comments on commit d69efe0

Please sign in to comment.