英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论