2

I am trying to create a logging feature on my RoR application that logs all the actions performed by the user on a given controller in a model. I tried implementing it with filters but they didn't solve my problem because they didn't allow me to properly log "create" actions.

"Create" actions are tricky because, when the before/after filters are called the action hasn't been saved yet, therefore, I don't have the corresponding id of the model (which I need).

I know I could use "after_commit", but this would greatly increase the complexity of the logging feature, since the "parameters" saved in each log entry are exposed to the controller, but not to the model.

Is there a way to dynamically add an "after_commit" filter to an instance of ActiveRecord?

Vicente
  • 232
  • 1
  • 10

2 Answers2

0

Read this, I think this is nice solution: Notifications

bor1s
  • 4,081
  • 18
  • 25
0

This is how i log, i have a users controller create action like this:

def create
    @user = User.new(params[:user])
    if @user.save
        flash[:notice] = "Welcome, #{@user.username}"
        redirect_to(:controller => "users", :action => "home")
        session[:id] = @user.id
    else
        render("home")
    end
end

Now i would like to log that a user was created, then i do this:
First create an AuditLogger class in User.rb(model):

class User < ActiveRecord::Base
    ...some stuff other....
    class AuditLogger < Logger
       def format_message(severity, timestamp, progname, msg)
       "#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n"
    end 
end

Then back to the controller(users.rb)

def create
    @user = User.new(params[:user])
    if @user.save
        logfile = File.open("#{Rails.root}/log/my_log.log", 'a')    
        audit_log = AuditLogger.new(logfile)
        audit_log.info "#{@user.firstname} was created successfully"
        redirect_to(:controller => "users", :action => "home")
    else
        render("home")
    end
end

Also you will need to create a file in your log directory called my_log.log. Hopefully it should be able to log. I know its not the best solution and there i are better ways of doing it, but at the time i needed something to work urgently, so i stuck with it.

Checkout these links:
rails logging tips
alternative logging solution

Community
  • 1
  • 1
Hishalv
  • 3,052
  • 3
  • 29
  • 52