在rails4 logger中添加唯一ID以标识请求和响应

时间:2015-01-07 05:05:41

标签: ruby-on-rails ruby-on-rails-4 logging

我在我的工作文件中添加了以下rails logger。

@@logger = Logger.new "log/rest_client.log"
  @@logger.level = Logger::DEBUG
end


begin
  @@logger.debug "The request #{url}"
  response = RestClient.get '#{url}'
  @@logger.debug "Successful response #{response}"
rescue => e
  @@logger.debug "Failure response #{e.message}"
end

我想在记录器(rest_client.log)中使用唯一ID识别请求和响应(成功或失败)。

现在日志

D, [2014-12-09T14:27:18.576498 #29871] DEBUG -- : The request https://api.bitfinex.com/v1/symbols
D, [2014-12-09T14:27:21.547365 #29874] DEBUG -- :Successful response ["btcusd","ltcusd","ltcbtc","drkusd","drkbtc","th1btc"]

我想要一些对请求和响应都唯一的东西,以确定两者属于同一个。

1 个答案:

答案 0 :(得分:1)

由于您在每一步都控制了日志消息的内容,因此您可以在每次发出请求时自己创建并使用唯一的ID。基于时间戳的ID将是唯一的。

一种可能的解决方案:

begin
  unique_id = "ID-" + Time.now.strftime("%Y%m%d-%H%M%S")
  @@logger.debug "#{unique_id}: The request #{url}"
  response = RestClient.get '#{url}'
  @@logger.debug "#{unique_id}: Successful response #{response}"
rescue => e
  @@logger.debug "#{unique_id}: Failure response #{e.message}"
end

记录:

D, [2014-12-09T14:27:18.576498 #29871] DEBUG -- : ID-20141209-142718: The request https://api.bitfinex.com/v1/symbols
D, [2014-12-09T14:27:21.547365 #29874] DEBUG -- : ID-20141209-142718: Successful response ["btcusd","ltcusd","ltcbtc","drkusd","drkbtc","th1btc"]