简体   繁体   English

使用每个请求的 ID 登录 Rails

[英]Logging in Rails with a per-request ID

I'm looking for a quick and easy way to generate a unique per-request ID in rails that I can then use for logging across a particular request.我正在寻找一种快速简便的方法来在 rails 中生成一个唯一的每个请求 ID,然后我可以使用它来记录特定请求。

Any solution should ideally not make too much use of the default logging code, as I'm running the application under both jruby and ruby.理想情况下,任何解决方案都不应过多使用默认日志记录代码,因为我正在 jruby 和 ruby​​ 下运行应用程序。

Backupify produced a great article about this: http://blog.backupify.com/2012/06/27/contextual-logging-with-log4r-and-graylog/ Backupify 对此发表了一篇很棒的文章: http ://blog.backupify.com/2012/06/27/contextual-logging-with-log4r-and-graylog/

We wanted the request_id (that is generated by rails and available at request.uuid to be present on all messages throughout the request. In order to get it into the rack logging (the list of parameters and the timing among others), we added it to the MDC in a rack middleware.我们希望 request_id(由 rails 生成并在request.uuid中可用)出现在整个请求中的所有消息中。为了将其放入机架日志记录(参数列表和时间等),我们添加了它到机架中间件中的 MDC。

application.rb:

config.middleware.insert_after "ActionDispatch::RequestId", "RequestIdContext"

app/controllers/request_id_context.rb: (had trouble finding it in lib for some reason) app/controllers/request_id_context.rb:由于某种原因在lib中找不到它)

class RequestIdContext
  def initialize(app)
    @app = app
  end

  def call(env)
    Log4r::MDC.get_context.keys.each {|k| Log4r::MDC.remove(k) }
    Log4r::MDC.put("pid", Process.pid)
    Log4r::MDC.put("request_id", env["action_dispatch.request_id"])
    @app.call(env)
  end
end

If you push jobs onto delay job/resque, put the request_id into the queue.如果您将作业推送到延迟作业/resque,请将 request_id 放入队列。 and in your worker pull it off and set into the MDC.并在您的工人中将其取下并放入 MDC。 Then you can trace the requests the whole way through然后您可以全程跟踪请求

It looks like lograge ( gem ) automatically puts request.uuid in your logs.看起来 lograge ( gem ) 会自动将request.uuid放入您的日志中。

They have this pattern: bfb1bf03-8e12-456e-80f9-85afaf246c7f他们有这种模式: bfb1bf03-8e12-456e-80f9-85afaf246c7f

This is now a feature of rails :这是rails 的一个特性

class WidgetsController < ApplicationController
  def get
    puts request.request_id
  end
end

也许log4rNDC特性对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM