Skip to content
Jan 14 / Rob

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"

6 Comments

leave a comment
  1. Jeremy Maziarz / Sep 11 2009

    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)”

  2. bernd / Aug 2 2010

    Very helpful thanks!

  3. John Thomas Marino / Jun 5 2011

    Here is a gem that makes log customization really easy:
    https://github.com/johmas/itslog

  4. Aina Anjary Fenomamy / Jun 29 2011

    Hi,
    nice tutorial :) 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?
    Thanks

  5. Aleks / Mar 11 2012

    Thanks Rob! :)

Trackbacks and Pingbacks

  1. Railsでcustom log(file)の作り方 « Kinopyo Blog
Leave a Comment