I use Devise in Rails 3. I want to see name of current_user in production.log.
I would like to configure rails like this:
config.log_tags = [:user_name]
I use Devise in Rails 3. I want to see name of current_user in production.log.
I would like to configure rails like this:
config.log_tags = [:user_name]
For anyone using Redis::Store @fjuillen's answer looks like this:
tested on rails 4.
Unfortunately log tags are evaluated only once at the very beginning of request delegation (in
Rails::Rack::Logger
middleware). At this stage there is no controller so any current_user helper is not yet available. No warden or even session set up yet, but there is a cookiejar at least, so if you store your session_id there you could restore the session or log session_id instead directly.I think the best alternative is to store username in the cookie directly at log_in, and destroy it with the session.
NOT WORKING:
But if you use devise, it uses warden raack middleware, so
env['warden']
should be available, so can you try?Even without warden, since you do have session available via
env['rack.session']
, if you store user id in session, you can do something likeAs @viktortron has said in his answer at
log_tags
initialization time we have not a propersession
objet available, but thesession_id
is in the request.If you are using a _database session_store_, as it is my case, you can rebuild the session ad-hoc:
This is how my
log_tags
are defined:The result is something like:
I found this little tricky but working solution.
Warden stores user information in session, but req.session is not available for logging.
So you must add this to config/application.rb
Then create file config/initializers/logging.rb
Now I see this for Anonymous:
and this for user:
I used this solution from Wojtek Kruszewski: https://gist.github.com/WojtekKruszewski
I tweaked a little bit for my project to only include id, but basically the same.
And create this initializer
I'm using Swards solution and it works like a charm. However using
begin..rescue
instead of Hash#has_key? is a performance killerResults speak for themselves