Ruby on Rails 5でAPIを作っていて、デフォルトのリクエストログにユーザーID(user_id)を追加したいということがあると思います。
このエントリでは、Ruby on Rails 5でLogrageを使ってリクエストログにユーザーIDを追加する方法を説明します。
 LogrageでユーザーIDをデフォルトのリクエストログに追加するには、下記のようにApplicationControllerにフックとなるappend_info_to_payloadメソッドを定義します。  
 append_info_to_payloadメソッドの中でrequestやcurrent_userからペイロードにユーザーIDをセットします。  
class ApplicationController < ActionController::API
  def append_info_to_payload(payload)
    super
    payload[:user_id] = current_user.try(:id)
  end
end
 Ruby on RailsをAPIアプリケーションとして使っていると、ApplicationControllerはActionController::BaseではなくActionController::APIを継承していると思います。  
 その場合、ベースクラスをActionController::APIに変更してあげる必要があります。  
下記のようにします。
Rails.application.configure do
  config.lograge.base_controller_class = 'ActionController::API'
end
APIと通常のWeb View両方使う場合は配列で指定します。
Rails.application.configure do
  config.lograge.base_controller_class = ['ActionController::API', 'ActionController::Base']
end
 ApplicationController#append_info_to_payloadで追加したuser_idをログに出力するには、下記のようにcustom_optionsで指定します。  
Rails.application.configure do
  config.lograge.enabled = true
  config.lograge.custom_options = lambda do |event|
    { user_id: event.payload[:user_id] }
  end
end
これで user_id がログに出力されます。
以上です。
このエントリでは、Ruby on Rails 5でLogrageを使ってリクエストログにユーザーIDを追加する方法を説明しました。
 
  
 
コメントを送る
コメントはブログオーナーのみ閲覧できます