0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

log_tagsでRails.loggerにsessionのuser_idを出力する

Last updated at Posted at 2022-11-17

環境

  • 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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?