Prepare user ID for all log messages in Rails

To track user activity for debugging purposes, we are considering adding a session registered in the user ID to each log message (if applicable). Our stack consists of Rails and Authlogic. I tried a couple of different routes, but none of them were 100% successful.

Since Authlogic does not save the user ID as plain text in the session data, we must wait for it to initialize. This only happens after initializing the ApplicationController and installing the active Authlogic controller. Because of this, we cannot rely on the code in config/application.rb . It seems to me that the only solution is to replace the registrar later.

I tried to create a new registrar class by subclassing Logger and overwriting the add() method:

 class UserLogger < Logger def add(severity, message = nil, progname = nil, &block) begin session = UserSession.find rescue return super(severity, message, progname, &block) end user = session.user if session if block_given? || !user return super(severity, message, progname, &block) end unless message.nil? message = "[#{user.id}] " + message end super severity, message, progname, &block end end 

This does not seem to affect the external log table. I also tried messing around with TaggedLogging, but that doesn't seem like a good solution, since you should throw some tagged code into a block.

I also tried to define config.log_tags in the application configuration by giving it Proc, but Authlogic threw the same error Authlogic::Session::Activation::NotActivatedError . Trying to catch this exception put Ruby in a very strange state, which seemed to be an endless loop somewhere and bound my processor 100%.

Is there a simple solution for this or one that I am completely lacking?

+4
source share
2 answers

Unable to access session object from request object. But you can access cookies .

So add this code after user login:

 cookies.signed[:user_id] = @user.id 

And add an initializer, for example:

 MyApp::Application.config.log_tags = [ -> request { "user-#{request.cookie_jar.signed[:user_id]}" } ] 

Now all your logs will have [user-980191314] or [user-] added.

+1
source

My project also uses its own registrar, and we connect it in /production.rb environments. Do you install the Rails recorder in production.rb?

 config.logger = ActiveSupport::TaggedLogging.new(UserLogger.new) 
0
source

Source: https://habr.com/ru/post/1444930/


All Articles