Lieven Cardoen
Lieven Cardoen

Reputation: 25959

Add session id to each log in Rails

Is there a way to add the session id to each log in Rails.

Now, I've added this in my environment.rb:

class Logger
  def format_message(severity, timestamp, progname, msg)
    "#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n" 
  end 
end

First of all, is this best-practice? And how do I add the session id?

Upvotes: 3

Views: 9362

Answers (4)

Binary Logic
Binary Logic

Reputation: 1547

Unfortunately this isn't easy with Rails log tags. Moreover, it clutters your logs to the point where they are unreadable.

I'd recommend something like timber, it captures session ids (and more) by simply augmenting your logs with metadata. It's automatic and you don't lose readability.

Upvotes: -1

jBilbo
jBilbo

Reputation: 1703

For Rails 3.2 with ActiveSupport::TaggedLogging, if you're using :cookie_store:

config.log_tags = [ :uuid, :remote_ip, 
                    lambda { |r| "#{r.cookie_jar.signed["_session_id"]["session_id"]}" } ]

Note: Change the "_session_id" with your :key value at config/initializers/session_store.rb

Upvotes: 1

phoet
phoet

Reputation: 18835

when you are working with rails 3.2 you can use log tags:

Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications DHH

with some luck, adding this to your environment might work:

config.log_tags = [:uuid, :remote_ip, :session_id]

UPDATE

for the unlucky, the solution is from the answer of @shigeya.

unfortunately rails does NOT provide a way to access your sessionid in a sane manner. you always have to rely on what rack is doing in it's internals... accessing the cookie_jar with your cookie key is the "recommended" way of doing so.

this is what i use for my application:

config.log_tags = [
  :host,
  :remote_ip,
  lambda { |request| "#{request.uuid}"[0..15] },
  lambda { |request| "#{request.cookie_jar["_session_id"]}"[0..15] },
]

output then looks like this:

[hamburg.onruby.dev] [127.0.0.1] [27666d0897c88b32] [BAh7B0kiD3Nlc3Np] Completed 200 OK in 298ms (Views: 286.2ms | ActiveRecord: 9.2ms)

Upvotes: 3

shigeya
shigeya

Reputation: 4922

Unfortunately, giving :session_id to log_tags don't work yet (as of May 23 2012), since there is no session_id in Rack middleware.

Since log_tags array accept a Proc object, and the proc object is invoked with a request object, I could configure the log_tags following way:

config.log_tags = [ :uuid, :remote_ip,
                    lambda {|req| "#{req.cookie_jar["_session_id"]}" } ]

It's working with Rails 3.2.3, with ActiveRecord's session store is in use.

Upvotes: 6

Related Questions