简体   繁体   中英

How to log API requests in Rails?

I have a Rails application which has an API at /api/v1/...

I would like to be able to log all the requests that are done to the API, and I know they are in the log file, but is there any alternative so that all the requests can be permanently stored?

How do you deal with this in Rails?

A slightly more expanded explanation for the benefit of the commenter above, since I just had to do this.

  • Create a new model to store each request. This one is called ApiRequest .
class CreateApiRequests < ActiveRecord::Migration[5.2]
  def change
    create_table :api_requests do |t|
      t.belongs_to :api_key
      t.string :endpoint
      t.string :remote_ip
      t.json :payload
      t.datetime :created_at
    end
  end
end
  • Use a "before_action" filter in each API Controller to call a method that will create a new ApiRequest entry and store it.
module Api
  module V2
    class SomeController < ::ApplicationController

      before_action :log_api_request

      <controller methods>

Our application is API-only, so we inherit from the top-level ApplicationController

  • The method log_api_request creates an ApiRequest object as suggested by Carson above.
  def log_api_request
    ApiRequest.create(
      api_key: api_key,
      endpoint: request.fullpath,
      remote_ip: request.remote_ip,
      payload: params,
      created_at: Time.now.iso8601
    )
  end

The gist is to create your own database table/model to log API requests by calling the create consistently from the controller methods as that doesn't require any additional components beyond what's already available.

Create a new logging class

ApiLog
  user_id:integer
  endpoint:string

In the controller endpoint, create a log entry on every request.

Api::v1::SomethingController
  def index
    ApiLog.create(endpoint: 'Something: Index'
    ....
  end

Continue this in all of the necessary API controllers. With the endpoints flagged, you can do queries of ApiLog, by endpoint, of any specific, user, within any time frame. The created_at attribute of ApiLog will serve as the time the API request was received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM