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

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

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 中添加以下配置:

SemanticLogger.configure do |config|
  # 现有的配置

  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

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

# 发起 API 调用
response = HTTParty.get('https://api.example.com/users', headers: { 'Authorization' => 'Bearer token' })

# 记录 API 调用
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

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

Now you can log as mentioned below

# 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)

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:

确定