Skip to content

Instantly share code, notes, and snippets.

@x1wins
Last active September 19, 2023 05:02
Show Gist options
  • Save x1wins/091125dd86205ef38e34e17109fa1b65 to your computer and use it in GitHub Desktop.
Save x1wins/091125dd86205ef38e34e17109fa1b65 to your computer and use it in GitHub Desktop.
Ahoy ApplicationController for REST API request, response log
class ApplicationController < ActionController::Base
after_action :track_action
protected
def track_action
ahoy.track "Called API", request.path_parameters.merge(log_request, log_response)
end
private
# https://stackoverflow.com/a/28687803/1399891
def log_request
http_envs = {}.tap do |envs|
request.headers.each do |key, value|
envs[key] = value if key.downcase.starts_with?('http') || key.downcase.starts_with?('x') || key.downcase.starts_with?('content')
end
end
{
request: {
method: request.method,
to: request.url,
from: request.remote_ip,
headers: http_envs,
body: parse_json(request.raw_post)
}
}
end
def log_response
{
response: {
status: response.status,
headers: response.headers,
body: parse_json(response.body)
}
}
end
def parse_json string
JSON.parse(string) rescue string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment