Hom*_*ith 6 api logging ruby-on-rails
我有一个Rails应用程序,它的API位于/ api/v1/...
我希望能够记录对API执行的所有请求,并且我知道它们在日志文件中,但是有没有替代方法可以永久存储所有请求?
你如何在Rails中处理这个问题?
小智 1
为了上面评论者的利益,稍微扩展一下解释,因为我只需要这样做。
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
Run Code Online (Sandbox Code Playgroud)
module Api
module V2
class SomeController < ::ApplicationController
before_action :log_api_request
<controller methods>
Run Code Online (Sandbox Code Playgroud)
我们的应用程序仅支持 API,因此我们继承自顶级 ApplicationController
log_api_request
按照上面 Carson 的建议创建一个 ApiRequest 对象。 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
Run Code Online (Sandbox Code Playgroud)
要点是通过从控制器方法一致地调用 create 来创建您自己的数据库表/模型来记录 API 请求,因为除了现有可用组件之外,不需要任何其他组件。
归档时间: |
|
查看次数: |
899 次 |
最近记录: |