Skip to content

Instantly share code, notes, and snippets.

@itsderek23
Created June 20, 2018 14:45
Show Gist options
  • Save itsderek23/39729ff8dbf08b57f31570b3a942a159 to your computer and use it in GitHub Desktop.
Save itsderek23/39729ff8dbf08b57f31570b3a942a159 to your computer and use it in GitHub Desktop.
Add the Response Content Length to Scout Context
# Reports the response body content length to Scout as a "Response-Content-Length" context attribute on transactions.
# This attribute is useful to correlate against slow requests that spend significant time in the view portion of a request,
# which is often related to rendering a large amount of data.
#
# To install in a Rails app:
# add to RAILS_ROOT/config/initializers/content_length_middleware.rb
# Rack::Sendfile is typically early in the middleware stack.
# Want to ensure +ContentLengthMiddleware+ executes after +Rack::ContentLength+ returns.
Rails.application.config.middleware.use Rack::ContentLength # Adding this seems to prevent DevTrace from rendering.
Rails.application.config.middleware.insert_before Rack::ContentLength, "ScoutApm::ContentLengthMiddleware"
module ScoutApm
class ContentLengthMiddleware
CONTENT_LENGTH = 'Content-Length'.freeze
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @response = @app.call(env)
if content_length
ScoutApm::Context.add("Response-Content-Length" => content_length) # in bytes
end
[@status, @headers, @response]
end
private
def content_length
@headers[CONTENT_LENGTH]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment