To log the raw HTTP request and response in Rails, you can use the built-in logging capabilities of the Rack middleware. By adding custom middleware to your Rails application, you can intercept and log the raw HTTP request and response data before it is processed by the application.

Here's how you can do it:

  1. Create a New Middleware: In your Rails application, create a new Ruby file for the custom middleware. For example, you can create a file called http_logger.rb in the middlewares directory under the app folder.

    # app/middlewares/http_logger.rb class HttpLogger def initialize(app) @app = app end def call(env) request = # Log the raw HTTP request "HTTP Request:" " Method: #{request.request_method}" " URL: #{request.url}" " Headers: #{request.env}" " Body: #{}" status, headers, response = # Log the raw HTTP response "HTTP Response:" " Status: #{status}" " Headers: #{headers}" " Body: #{response.body.join}" [status, headers, response] end end
  2. Configure Middleware in Application: Open the config/application.rb file and add the following line to the config block. This will insert your custom middleware into the middleware stack.

    # config/application.rb config.middleware.use HttpLogger
  3. Adjust Log Level (Optional): By default, Rails logs everything with the log level of INFO (severity level 1). If you want to see the HTTP request/response logs in the console during development, you may need to adjust the log level in config/environments/development.rb.

    # config/environments/development.rb config.log_level = :debug
  4. Restart the Rails Server: After making these changes, restart your Rails server to apply the new middleware.

With this setup, all incoming HTTP requests and outgoing HTTP responses will be logged in your Rails log files. The log entries will contain detailed information about the request method, URL, headers, and body, as well as the response status, headers, and body.

Please note that logging the raw HTTP request and response can generate a large amount of data and may not be suitable for production environments or high-traffic applications. Use this approach with caution and consider enabling it only in development or staging environments where detailed logging is helpful for debugging and troubleshooting. In production, it's better to use more selective and structured logging.

Have questions or queries?
Get in Touch