What we want here is to create a customized access logging for Ruby On Rails that is human readable and user-friendly. By user-friendly, I mean that is readable by ordinary user and contents are filtered.

Customized logging in Ruby On Rails Using the Logger Class


On config/environment.rb , set up the format of logging. To do so, place the code below just before the closing end on the environment.rb

class Logger
 def format_message(severity, timestamp, progname, msg)
  "[#{timestamp.strftime("%Y-%m-%d %H:%M:%S")}] [#{severity}]  #{msg}\n"

This would output the log as something like this:

[2011-06-21 13:52:21] [INFO]  YOUR MESSAGE HERE.

On application_controller.rb

Add at the top part a before_filter to make the variable applicable to all:

before_filter :login_check

and the function as

def login_check

 @log_file = "#{RAILS_ROOT}/log/#{Time.zone.now.strftime("%B-%Y")}.log"

 unless File.exists?(@log_file)
  @logger = Logger.new(@log_file, "monthly")
  @logger.datetime_format = "%Y-%m-%d %H:%M:%S"
  file = open(@log_file, File::WRONLY | File::APPEND)
  @logger = Logger.new(file, "monthly")
  @logger.datetime_format = "%Y-%m-%d %H:%M:%S"

Now all you need to do is call:

@logger.info("YOUR MESSAGE HERE")

to log certain events. I usually placed this at the end or at parts on the controller that I think would be useful.

You can always customized furthermore the log files contents or directory placed. From the example above, log files are placed inside the log/access folder and has a filename with the following format - [MONTH]-[YEAR].log

This is to make sure that the log files are organized by month.

No comments :

Post a Comment