How to log user_name in Rails?

后端 未结 12 1697
遇见更好的自我
遇见更好的自我 2020-12-15 06:52

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_na         


        
12条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 07:44

    Added 2013-03-07:

    In Rails 4 encrypted_cookie_store is the default session store. This is how you can access session data:

    session_data = req.cookie_jar.signed[ "_qnaire_session" ]
    

    And it looks like warden_data looks differently in my new app, e.g.: [[542], "$2a$10$e5aYxr/PIp6OOj8jzE7mke"], where first item is user id.

    Here's my current snippet: https://gist.github.com/wojt-eu/5109643

    Previous version:

    This is what I came up with:

    config.log_tags = [
      :remote_ip,
      ->(req){
        session_data = req.cookie_jar.signed[ "_qnaire_session" ]
        warden_data = session_data["warden.user.provider_user.key"]
        if warden_data
          '#' + warden_data[1][0].to_s
        else
          "guest"
        end
      }
    ]
    

    _qnaire_session can be replaced with instance.config.session_options[:key] or via singleton: Rails.application.config.session_options[:key]

    I have ProviderUser model, hence warden.user.provider_user.key. I suppose with User model this would be warden.user.user.key.

    It's messy, but it does not affect normal authentication process, middleware stack order etc. If it breaks during some update only tagging logs will be affected, which I should quickly notice while looking at development logs.

提交回复
热议问题