CodexBloom - Programming Q&A Platform

Rails 7.1: How to handle custom middleware for request logging without affecting performance?

πŸ‘€ Views: 97 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
ruby rails middleware

I've searched everywhere and can't find a clear answer. I'm trying to implement custom middleware in my Rails 7.1 application to log request details for debugging purposes. However, I've noticed that it seems to add significant latency to my requests, which is concerning for a production environment. Here’s a simplified version of my middleware: ```ruby class RequestLogger def initialize(app) @app = app end def call(env) start_time = Time.now status, headers, response = @app.call(env) duration = Time.now - start_time log_request(env, duration) [status, headers, response] end private def log_request(env, duration) Rails.logger.info "#{env['REQUEST_METHOD']} #{env['PATH_INFO']} - #{duration.round(2)}s" end end ``` I’ve inserted this middleware into my application like this: ```ruby # config/application.rb config.middleware.use RequestLogger ``` After adding this, when I check the logs, I see the logging works as expected, but my response times are significantly longer. In my testing, a request that usually takes 50ms now takes around 150ms. I suspect that the logging is synchronous and is blocking the request thread. I've tried using `ActiveSupport::Notifications` to handle logging in an asynchronous manner, but it’s not clear to me how to implement that correctly. Is there a better approach to implement logging that minimizes performance impact? Should I offload this logging to a background job or maybe use a different strategy? Any insights on best practices for this kind of middleware in a Rails application would be greatly appreciated. This is happening in both development and production on Debian. Any ideas what could be causing this?