Class: LevoRailsmiddleware::Middleware
- Inherits:
-
Object
- Object
- LevoRailsmiddleware::Middleware
- Defined in:
- lib/levo_rails_middleware/middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
5 6 7 8 9 10 11 |
# File 'lib/levo_rails_middleware/middleware.rb', line 5 def initialize(app) @app = app @sender = Sender.new(LevoRailsmiddleware.configuration.remote_url) rescue => e LevoRailsmiddleware.log_exception("initializing middleware", e) @initialization_failed = true end |
Instance Method Details
#call(env) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/levo_rails_middleware/middleware.rb', line 13 def call(env) # Skip processing if initialization failed or middleware is disabled return @app.call(env) if @initialization_failed || !LevoRailsmiddleware.configuration.enabled # Skip excluded paths path = env['PATH_INFO'] || "" return @app.call(env) if should_skip?(path) # Skip based on sampling rate return @app.call(env) if rand > LevoRailsmiddleware.configuration.sampling_rate start_time = Time.now # Preserve the original request body request_body = env['rack.input'].read env['rack.input'].rewind # Process the request through the app status, headers, body = @app.call(env) end_time = Time.now # Calculate the request duration duration_ms = ((end_time.to_f - start_time.to_f) * 1000).round # Save the original input stream saved_input = env['rack.input'] env['rack.input'] = StringIO.new(request_body) # Create the request/response entry and send it begin entry = Entry.new(start_time, duration_ms, env, status, headers, body) @sender.send_async(entry) rescue => e LevoRailsmiddleware.log_exception("processing request", e) ensure # Restore the original input stream env['rack.input'] = saved_input end [status, headers, body] rescue => e LevoRailsmiddleware.log_exception("middleware execution", e) @app.call(env) # Ensure we still call the app even if our middleware fails end |