Alex Rivera | Logout

Logging in Rails with a per-request ID

Asked 2011-08-01T11:02:38.010
11

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.

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.

Edit
Report

1 Answer

7

Backupify produced a great article about this: 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.

application.rb:

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

app/controllers/request_id_context.rb: (had trouble finding it in lib for some reason)

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. and in your worker pull it off and set into the MDC. Then you can trace the requests the whole way through

answered 2013-02-22T03:13:19.987

Your Answer