Home » Headline, Web Development, projects

Ruby on Rails custom logging

4 March 2009

As one of my rails projects has finally gone to production, one of the more important things I needed consider was how to properly monitor user activity in my application.

Beyond tracking things via google analytics, I wanted to establish some custom log files (beyond spitting everything out into production.log). My first goal: track users that are logging in, and from where.

As I do with most things, I first scour the net for advice so I don’t have to reinvent the wheel. Sure I could probably figure it out on my own, but given how aggressively “best practices” seem to change with rails, I tend to do a lot of homework before trying something new.

This lead to frustration. I found a lot of material on the standard logging, and even a few posts on using log4, but very little on just using the standard logger to spit out a formatted message to a new file.

Finally I found this helpful post which seems to be about two years old, and a little sparse on details. Frankly, I was a little shocked.. even modern posts on custom logging were referencing this old article.

Anyhow, here was my final solution (which worked better than what was outlined in the article above):

create /config/auditlogger.rb

add this to it:

class AuditLogger < Logger
def format_message(severity, timestamp, progname, msg)
“#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n”
end
end

edit config/environment.rb

add this near the top: require File.join(File.dirname(__FILE__), ‘auditlogger’)

add this inside the Rails::Initializer.run do |config|

audit_logfile = File.open(”#{RAILS_ROOT}/log/audit.log”, ‘a’)
audit_logfile.sync = true
AUDIT_LOG = AuditLogger.new(audit_logfile)

(note: you actually need the all caps AUDIT_LOG)

Add this to track a user login inside your login_controller action:

AUDIT_LOG.info(request.remote_ip + ” Logged in: ” + @user.login )

Restart your rails application, watch all the goodies show up in log/audit.log

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.