I wrote a middleware (actually two, but they do the same with different implementations) that logs information about signed in scopes in a Rails + Devise application. The solution works with multiple logins (like having a person logged both as an Admin
and a User
). I tested against Rails 4 and Devise HEAD
, but it should work fine in any Rails 3 application.
This solution doesn't use the log_tags
configuration option since it isn't very helpful when you need to retrieve information stored in cookies/session. That information isn't 'ready' when the Rails::Rack::Logger
is executed, since it happens way down in the middleware chain.
Add one of the following implementations to your application load path and use the following configuration to add the middleware to your application stack:
# application.rb
config.app_middleware.insert_after("Warden::Manager", "Devise::TaggedLogging")
You logs will end up looking like this:
Started GET "/projects/1/users/1/02-2013" for 127.0.0.1 at 2013-02-23 13:42:56 -0300
User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
[current user: 1] Processing by ReportsController#show as HTML
[current user: 1] Parameters: {"project_id"=>"1", "user_id"=>"1", "month"=>"02-2013"}
[current user: 1] Project Load (1.1ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", "1"]]
[current user: 1] User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "1"]]
[current user: 1] Rendered reports/show.html.erb within layouts/application (189.8ms)
[current user: 1] User Load (1.1ms) SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
[current user: 1] Project Load (0.5ms) SELECT "projects".* FROM "projects" ORDER BY "projects"."name" ASC
[current user: 1] Rendered layouts/shared/_header.html.erb (15.4ms)
[current user: 1] Completed 200 OK in 1811ms (Views: 306.9ms | ActiveRecord: 5.9ms)
Beware that the first line doesn't have any related information since it's logged by Rails::Rack::Logger
, where you don't have the session data yet.
Awesome! Thanks!