Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
cbz Avatar asked Aug 01 '11 11:08

cbz


3 Answers

This is now a feature of rails:

class WidgetsController < ApplicationController
  def get
    puts request.request_id
  end
end
like image 113
davetron5000 Avatar answered Oct 03 '22 20:10

davetron5000


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

like image 25
kbrock Avatar answered Oct 03 '22 20:10

kbrock


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

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

like image 25
Benjamin Crouzier Avatar answered Oct 03 '22 21:10

Benjamin Crouzier