使用 `log_tags` 将会把会话的 `user_id` 输出到 `Rails.logger` 中

环境

    • Rails 7.0.4

 

    redis 6.2

如果是cookie_store的情况下

# config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store, ... 

# config/environments/development.rb
Rails.application.configure do

  config.log_tags = [
    :request_id,
    lambda { |req|
      session_key = (Rails.application.config.session_options || {})[:key]
      session = req.cookie_jar.encrypted[session_key] || {}

      "user_id: #{session['user_id'] || '-'}"
    }
  ]
end

如果使用redis_store的话

# Gemfile
gem 'redis-actionpack'

# config/initializers/session_store.rb
Rails.application.config.session_store :redis_store, ...

# config/environments/development.rb
Rails.application.configure do

  config.log_tags = [
    :request_id,
    lambda { |req|
      session_options = Rails.application.config.session_options || {}
      session_id = req.cookie_jar[session_options[:key]]
      session = if session_id.present?
                  redis = Redis.new(session_options[:servers])
                  key = [
                    session_options.dig(:servers, :namespace),
                    Rack::Session::SessionId.new(session_id).private_id
                  ].compact.join(':')
                  val = redis.get(key)
                  Marshal.load(val) if val
                end || {}

      "user_id: #{session['user_id'] || '-'}"
    }
  ]
end

似乎在Redis的key中使用了Rack::Session::SessionId.new(session_id).private_id。内部的生成逻辑是2::”#{Digest::SHA256.hexdigest(session_id)}。

 

以下这篇文章对于对话周边的代码阅读非常有参考价值:
https://blog.freedom-man.com/rails-session-codereading

广告
将在 10 秒后关闭
bannerAds