public
Last active

Rails 3.2 Tagged Logger examples

  • Download Gist
proc.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12
# somewhere in your middleware stack...
# request.env['yourapp.someid'] = "1337"
 
YourApp::Application.configure do
config.log_tags = [
-> request {
request.env['yourapp.someid']
}
]
end
 
# [1337] Processing by ProjectsController#index as HTML
string.rb
Ruby
1 2 3 4 5
YourApp::Application.configure do
config.log_tags = ["Static"]
end
 
# [Static] Processing by ProjectsController#index as HTML
symbol.rb
Ruby
1 2 3 4 5
YourApp::Application.configure do
config.log_tags = [:uuid]
end
 
# [71ba53fd717c67a6677a058f4a5acdf4] Processing by ProjectsController#index as HTML

What about logging some information from the current session? I was trying to do the following. config.log_tags = [ lambda { |request| request.session[:user_id] }], but at this point request.session always seems to be an empty hash.

Does this imply that the 'session middleware' isn't called yet at this stage?

Might be. You could always stuff that in the rack env in another middleware.

Could you give me an example for that? Because I don't fully understand it.
When the request.session is still {} at this point: https://github.com/rails/rails/blob/master/railties/lib/rails/rack/logger.rb#L32, how would another middleware be able to add something from the session to the rack env before that?

Only other option I can think of is to write a middleware like this. (which is called after the logger)

class UserLogger
  def initialize(app)
    @app = app
  end

  def call(env)
    Rails.logger.tagged( env['rack.session']['user_id'] ) { @app.call(env) }
  end
end

Did you ever get this figured out? I was also hoping to add my userid from the session to my rails logs.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.