store all http request, response with ahoy gem

109 views Asked by At

I want made that all log will store database. therefore I try setup Ahoy gem in my Rails Api only Project. Ahoy is awesome gem. but there is not Best pratice on README.md of Ahoy github.

i hope store http request header, reponse header and body with Ahoy. this code is track_action for storing event in ApplicationController.

class ApplicationController < ActionController::Base
  after_action :track_action

  protected

  def track_action
     ahoy.track "Viewed #{controller_name}##{action_name}", { request: { header: request.headers },
                                                              response: { headers: response.headers, body: JSON.parse(response.body) } }

  end
end

but i got error.

Completed 500 Internal Server Error in 493ms (Views: 34.8ms | ActiveRecord: 89.1ms | Allocations: 317174)


  
SystemStackError (stack level too deep):
  
app/controllers/application_controller.rb:14:in `track_action'

What is Best practice ahoy.track for storing all request, response log?

storing all http request, response with Ahoy gem

1

There are 1 answers

0
Engineer Waqas On

The issue is with request.headers as it is quite complex and includes various attributes and methods, and attempting to track it directly is causing the problem. They are 98 headers in my case:

request.headers.count    # => 98

which all can be checked:

request.headers.each { |header| print header }

Ways to Fix

  1. Store only HTTP headers and reject environment variables from request:

    request.headers.env.reject { |key| key.to_s.include?('.') }
    
  2. Store only specific request attributes:

    request.headers["HTTP_COOKIE"]
    

Performance Optimization

Decide which endpoints or actions are crucial for your analytics and log only those. Instead of logging the entire request or response (headers, body), choose only the necessary parts. You can also use background jobs instead of logging directly into the request/response cycle to avoid database performance issues.