如何使用Rails语义记录器记录整个请求(标头、正文等)。

huangapple go评论89阅读模式
英文:

How to log an entire request (headers, body, etc) using rails semantic logger

问题

我想记录任何外部API调用的 headers, body, params 以便自动记录,我正在使用 rails_semantic_logger,是否有配置和定制可以帮助我记录这些详情?

英文:

I want to log any external API call headers, body, params to be automatically logged, i am using rails_semantic_logger, is there any configuration and customisation that will help my to log these details?

答案1

得分: 1

在你的 config/initializers/semantic_logger.rb 中添加以下配置:

  1. SemanticLogger.configure do |config|
  2. # 现有的配置
  3. config.add_appender(
  4. io: STDOUT,
  5. level: :debug,
  6. formatter: proc { |_, _, _, payload|
  7. "#{payload[:method]} #{payload[:url]}\n" \
  8. "Headers: #{payload[:headers].inspect}\n" \
  9. "Body: #{payload[:body]}\n" \
  10. "Params: #{payload[:params].inspect}\n"
  11. }
  12. )
  13. end

现在,你可以按照下面的方式记录日志:

  1. # 发起 API 调用
  2. response = HTTParty.get('https://api.example.com/users', headers: { 'Authorization' => 'Bearer token' })
  3. # 记录 API 调用
  4. 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)

希望这对你有帮助。

英文:

Add below config in your config/initializers/semantic_logger.rb

  1. SemanticLogger.configure do |config|
  2. # existing configuration
  3. config.add_appender(
  4. io: STDOUT,
  5. level: :debug,
  6. formatter: proc { |_, _, _, payload|
  7. "#{payload[:method]} #{payload[:url]}\n" \
  8. "Headers: #{payload[:headers].inspect}\n" \
  9. "Body: #{payload[:body]}\n" \
  10. "Params: #{payload[:params].inspect}\n"
  11. }
  12. )
  13. end

Now you can log as mentioned below

  1. # Make an API call
  2. response = HTTParty.get('https://api.example.com/users', headers: { 'Authorization' => 'Bearer token' })
  3. # Log the API call
  4. 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)

I hope this will help you.

huangapple
  • 本文由 发表于 2023年5月18日 13:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定