How to log user_name in Rails?

后端 未结 12 1695
遇见更好的自我
遇见更好的自我 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:46

    Here's what I just added to config/initializers/logging.rb:

    Rails.configuration.log_tags = [
      :uuid,   # request UUID
      lambda { |req|
        # Credentials are (currently) in the format of:
        #
        #   ::
        #
        # So we have to split by '::' to obtain the user_id for logging.
        #
        # This will just output "User: nil" if there is no current session.
        "User: #{req.cookies['user_credentials'].to_s.split('::')[1]}"
      }
    ]
    

    This is for Authlogic. What you need to do might vary, so you should really dig in and see what your data exposes to you already.

    Step 1:

    See what the req object has available. Add this to config/initializers/logging.rb:

    Rails.configuration.log_tags = [
      lambda { |req|
        req.inspect
      }
    ]
    

    Then hit a page, and see what gets dumped.

    Step 2: See if your cookie jar has enough information, using the same technique:

    Rails.configuration.log_tags = [
      lambda { |req|
        req.cookies.inspect
      }
    ]
    

    (hit a request)

    An aside: Don't worry about putting in usernames/emails into the logs - user ID is good enough, and you can look it up in the database to get any extra metadata you need.

提交回复
热议问题