Custom log files for your ruby on rails applications
Sometimes logging is required but putting the messages in the Rails log isn’t the answer.For example you need to see the progress of customers through your order placement cycle, you ideally need this seperate to any other in a custom log file?
There is a solution and it’s easy… To create an order progress log, simply create a new instance of Logger and pass it a File instance for your own logfile.
Create a new model which inherits from Logger
class OrderProgressLogger < Logger
def format_message(severity, timestamp, progname, msg)
"#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n"
end
end
Create initializer called logs.rb in RAILS_ROOT/config/initializers with the following content:
order_progress_logfile = File.open("#{RAILS_ROOT}/log/order_progress.log", 'a')
order_progress_logfile.sync = true
ORDER_PROGRESS_LOG = OrderProcessLogger.new(order_progress_logfile)
After a restart of your mongrel or passenger ORDER_PROGRESS_LOG will be available through out your application.
You log to it just as you would DEFAULT_RAILS_LOGGER like so…
ORDER_PROGRESS_LOG.debug "Starting order placement method"
ORDER_PROGRESS_LOG.error "Could not create order record"




Thanks for writing this up. There is one typo though:
“ORDER_PROGRESS_LOG = ProcessLogger.new(order_progress_logfile)” should be “ORDER_PROGRESS_LOG = OrderProgressLogger.new(order_progress_logfile)”
Very helpful thanks!
Here is a gem that makes log customization really easy:
https://github.com/johmas/itslog
Hi,
and very helpful for the initializer, for tracking user activity(CRUD ), i have also created a class inherits from Logger, but I’ve putted the instance of it directly into the controller. and now I am planing to write a litle plugin for tracking user that i can use for any ROR application built. I have already checked if there is a plugin like that but I didn’t see. I guess there are many gem like paper-trail, acts_as_audited or itslog but i prefer to use a plugin. Any suggestions?
nice tutorial
Thanks
Thanks Rob!