我的记录器需要一个唯一的请求 ID,以便我可以跟踪日志文件中的每个请求。
到目前为止我得到了这个
REQUEST_ID = Digest::MD5.hexdigest(Time.now.to_f.to_s + $PID.to_s)
问题是我不知道把它放在哪里。我尝试将它放在类外的自定义记录器文件中。但它必须被缓存或什么的,因为我总是得到相同的散列。
有什么想法吗?
注意。我正在使用 Rails 3 和独立的 Passenger
更新:
Rails 3.2 :uuid 标签将不起作用。看看日志的格式有多糟糕:
[0909413851b79676cb06e0842d21c466] [127.0.0.1]
Started HEAD "/" for 127.0.0.1 at Tue Feb 21 14:08:25 -0300 2012
[0909413851b79676cb06e0842d21c466] [127.0.0.1] Processing by PagesController#home as HTML
[0909413851b79676cb06e0842d21c466] [127.0.0.1] bla
[0909413851b79676cb06e0842d21c466] [127.0.0.1] Rendered pages/home.html.erb within layouts/application (2.0ms)
在生产中这将是一团糟。注意到第一行之后的换行符了吗?现在想象一下日志在每秒处理许多请求的服务器中的样子。很难将请求与 URI 相关联
最佳答案
Rails 核心团队为您处理了这一切!
Rails 3.2 引入了 request.uuid
方法,该方法返回,嗯,唯一的请求标识符,如下所示:ab939dfca5d57843ea4c695cab6f721d
。
参见 release notes here .
也看看at this awesome screencast了解如何将这种新方法用于日志记录。
# config/environments/development.rb
config.log_tags = [:uuid, :remote_ip]
# log file
[ab939dfca5d57843ea4c695cab6f721d] [127.0.0.1]
Started GET "/" for 127.0.0.1 at 2012-01-27 21:52:58 +0000
[ab939dfca5d57843ea4c695cab6f721d] [127.0.0.1] Processing by ProductsController#index as HTML
[ab939dfca5d57843ea4c695cab6f721d] [127.0.0.1] Product Load (0.3ms) SELECT "products".* FROM "products"
[ab939dfca5d57843ea4c695cab6f721d] [127.0.0.1] Rendered products/index.html.erb within layouts/application (22.0ms)
[ab939dfca5d57843ea4c695cab6f721d] [127.0.0.1] Completed 200 OK in 81ms (Views: 73.1ms | ActiveRecord: 0.3ms)
[98eec5f8976586c1165b981797086b6a] [127.0.0.1]
关于ruby-on-rails - 如何在 Rails 中生成唯一的请求 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380083/