如何在 Rails 中记录 user_name? [英] How to log user_name in Rails?

查看:16
本文介绍了如何在 Rails 中记录 user_name?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3 中使用 Devise.我想在 production.log 中看到 current_user 的名称.

I use Devise in Rails 3. I want to see name of current_user in production.log.

我想像这样配置导轨:

config.log_tags = [:user_name]

推荐答案

我发现这个有点棘手但有效的解决方案.

I found this little tricky but working solution.

Warden 将用户信息存储在 session 中,但 req.session 不可用于日志记录.

Warden stores user information in session, but req.session is not available for logging.

所以你必须把它添加到 config/application.rb

So you must add this to config/application.rb

config.middleware.delete(ActionDispatch::Cookies)
config.middleware.delete(ActionDispatch::Session::CookieStore)
config.middleware.insert_before(Rails::Rack::Logger, ActionDispatch::Session::CookieStore)
config.middleware.insert_before(ActionDispatch::Session::CookieStore, ActionDispatch::Cookies)

然后创建文件 config/initializers/logging.rb

Then create file config/initializers/logging.rb

Rails.configuration.log_tags = [
  proc do |req|
    if req.session["warden.user.user.key"].nil?
      "Anonym"
    else
      "user_id:#{req.session["warden.user.user.key"][0][0]}"
    end
  end
]

现在我看到这个匿名:

[Anonym] Served asset ...

这对于用户来说:

[user_id:1] Served asset ...

这篇关于如何在 Rails 中记录 user_name?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆