在 rails4 记录器中添加唯一标识以标识请求和响应

Adding unique id in rails4 logger to identify the request and response

我在我的工作文件中添加了以下 rails 记录器。

@@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"]

我想要一些对请求和响应都是唯一的东西来标识它们属于同一个。

由于您在每一步都控制了日志消息的内容,因此您可以在每次发出请求时自己创建和使用一个唯一的 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"]