Add Session ID to Each Log in Rails

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

Now I have added this to 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 the best practice? And how to add a session id?

+3
source share
4 answers

when you work with rails 3.2, you can use log tags:

Updating Rails :: Rack :: Logger middleware to apply any tags set to config.log_tags for the new ActiveSupport :: TaggedLogging Rails.logger. This makes it easy to mark log lines with debugging information similar to the subdomain and request identifier - both very useful in debugging DHH multi-user production applications.

with luck, adding this to your environment may work:

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

UPDATE

for the loser, the solution is taken from @shigeya's answer.

Unfortunately, rails does NOT provide a way to access your sessionid in a reasonable way. you always have to rely on what the rack does inside it ... accessing the cookie_jar with your cookie key is the โ€œrecommendedโ€ way to do this.

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] }, ] 

The output is as follows:

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

Unfortunately, providing :session_id before log_tags does not work yet (as of May 23, 2012), because there is no session_id in the Rack middleware.

Since the log_tags array accepts a Proc object, and the proc object is called with the request object, I can configure log_tags as follows:

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

Works with Rails 3.2.3 using ActiveRecord session storage.

+5
source

For Rails 3.2 with ActiveSupport::TaggedLogging if you use :cookie_store :

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

Note. Change "_session_id" to :key value config/initializers/session_store.rb

+1
source

Unfortunately, this is not easy with Rails log tags. In addition, it clutters your magazines to the place where they are not read.

I would recommend something like timber , it captures session identifiers (and more), just increasing your logs with metadata. It is automatic, and you do not lose readability.

0
source

Source: https://habr.com/ru/post/1387846/


All Articles