简体   繁体   中英

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.

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

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

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

This is now a feature of rails :

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

也许log4rNDC特性对你有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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