Rails セマンティック ロガーを使用してリクエスト全体 (ヘッダー、本文など) をログに記録する方法
概要
外部 API 呼び出しのヘッダー、本文、パラメータを自動的にログに記録したいのですが、rails_semantic_logger を使用しています。これらの詳細をログに記録するのに役立つ設定やカスタマイズはありますか?
解決策
config/initializers/semantic_logger.rb に以下の設定を追加します。
SemanticLogger.configure do |config|
# existing configuration
config.add_appender(
io: STDOUT,
level: :debug,
formatter: proc { |_, _, _, payload|
"#{payload[:method]} #{payload[:url]}\n" \
"Headers: #{payload[:headers].inspect}\n" \
"Body: #{payload[:body]}\n" \
"Params: #{payload[:params].inspect}\n"
}
)
end
これで、以下のようにログを記録できるようになります
# Make an API call
response = HTTParty.get('https://api.example.com/users', headers: { 'Authorization' => 'Bearer token' })
# Log the API call
logger.debug('External API call', method: response.request.http_method, url: response.request.last_uri.to_s, headers: response.request.headers, body: response.request.body, params: response.request.params)
これがお役に立てば幸いです。