How to log user_name in Rails?

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

    I'm using Swards solution and it works like a charm. However using begin..rescue instead of Hash#has_key? is a performance killer

    require 'benchmark/ips'
    
    good_hash = { 'warden.user.admin_user.key' => [[1]]}
    bad_hash = {}
    
    Benchmark.ips do |x|
      x.report('begin+rescue good hash') { good_hash['warden.user.admin_user.key'][0][0] }
      x.report('has_key good hash') do
        good_hash.has_key?('warden.user.admin_user.key') &&
            good_hash['warden.user.admin_user.key'][0][0]
      end
    
      x.report('begin+rescue bad hash') { bad_hash['warden.user.admin_user.key'][0][0] rescue nil }
      x.report('has_key bad hash') do
        if bad_hash.has_key?('warden.user.admin_user.key')
          bad_hash['warden.user.admin_user.key'][0][0]
        end
      end
    
      # Compare the iterations per second of the various reports!
      x.compare!
    end
    

    Results speak for themselves

    Comparison:
        has_key bad hash:  4870164.1 i/s
    begin+rescue good hash:  3544134.7 i/s - 1.37x slower
       has_key good hash:  2127500.6 i/s - 2.29x slower
    begin+rescue bad hash:     4468.2 i/s - 1089.95x slower
    

提交回复
热议问题