Better Rails Logs: Current User Request Context

Ever gone to look at logs to investigate a bug reported by a user? Ever looked at your logs and had no idea what that user was doing?

Better logging to the rescue!

Rails’ config supports log_tags, which has some built in options such as subdomain and request_id but it also supports arbitrary procs.

The below config put into config/application.rb will produce logs with added tags (assuming your user_id is stored on the session):

config.log_tags = [
  :request_id,
  ->(req) {
    session_key = (Rails.application.config.session_options || {})[:key]
    session_data = req.cookie_jar.encrypted[session_key] || {}
    user_id = session_data["user_id"] || "guest"
    "user: #{user_id.to_s}"
  }
]

With these changes your logs will now have additional context

[some-request-id] [user: 123] ...

or if it’s a non logged in user

[some-request-id] [user: guest] ...

Need even more context? Check out https://github.com/remind101/request_id, which also can hook into background job logging via Sidekiq middleware, which can be a whole other layer of helpful.

Now that we’ve logged more data and are in log nirvana, make sure to think about GDPR compliance ;)