cbz
cbz

Reputation: 1764

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.

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.

Upvotes: 10

Views: 11969

Answers (4)

davetron5000
davetron5000

Reputation: 24841

This is now a feature of rails:

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

Upvotes: 3

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41905

It looks like lograge (gem) automatically puts request.uuid in your logs.

They have this pattern: bfb1bf03-8e12-456e-80f9-85afaf246c7f

Upvotes: 5

kbrock
kbrock

Reputation: 1017

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

Upvotes: 7

rsp
rsp

Reputation: 23373

Maybe the NDC feature of log4r is usefull to you.

Upvotes: 0

Related Questions