Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log something in Rails in an independent log file?

People also ask

How do I create a log file in rails?

If you want to change all the default logging for that specific model, you can simply use User. logger = Logger. new(STDOUT) or wherever you want to log to. In the same way, ActiveRecord::Base.

Where are rails logs stored?

In a Rails app, logs are stored under the /log folder.

How do I create a log file in Ruby?

Since the logger library comes with Ruby, there's no need to install any gems or other libraries. To begin using the logger library, simply require 'logger' and create a new Logger object. Any messages written to the Logger object will be written to the log file.


You can create a Logger object yourself from inside any model. Just pass the file name to the constructor and use the object like the usual Rails logger:

class User < ActiveRecord::Base
  def my_logger
    @@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
  end

  def before_save
    my_logger.info("Creating user with name #{self.name}")
  end
end

Here I used a class attribute to memoize the logger. This way it won't be created for every single User object that gets created, but you aren't required to do that. Remember also that you can inject the my_logger method directly into the ActiveRecord::Base class (or into some superclass of your own if you don't like to monkey patch too much) to share the code between your app's models.


Update

I made a gem based on the solution below, called multi_logger. Just do this in the initializer:

MultiLogger.add_logger('post')

and call

Rails.logger.post.error('hi')
# or call logger.post.error('hi') if it is accessible.

and you are done.

If you want to code it yourself, see below:


A more complete solution would be to place the following in your lib/ or config/initializers/ directory.

The benefit is that you can setup formatter to prefix timestamps or severity to the logs automatically. This is accessible from anywhere in Rails, and looks neater by using the singleton pattern.

# Custom Post logger
require 'singleton'
class PostLogger < Logger
  include Singleton

  def initialize
    super(Rails.root.join('log/post_error.log'))
    self.formatter = formatter()
    self
  end

  # Optional, but good for prefixing timestamps automatically
  def formatter
    Proc.new{|severity, time, progname, msg|
      formatted_severity = sprintf("%-5s",severity.to_s)
      formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
      "[#{formatted_severity} #{formatted_time} #{$$}] #{msg.to_s.strip}\n"
    }
  end

  class << self
    delegate :error, :debug, :fatal, :info, :warn, :add, :log, :to => :instance
  end
end

PostLogger.error('hi')
# [ERROR 2012-09-12 10:40:15] hi

A decent option that works for me is to just add a fairly plain class to your app/models folder such as app/models/my_log.rb

class MyLog
  def self.debug(message=nil)
    @my_log ||= Logger.new("#{Rails.root}/log/my.log")
    @my_log.debug(message) unless message.nil?
  end
end

then in your controller, or really almost anywhere that you could reference a model's class from within your rails app, i.e. anywhere you could do Post.create(:title => "Hello world", :contents => "Lorum ipsum"); or something similar you can log to your custom file like this

MyLog.debug "Hello world"

Define a logger class in (say) app/models/special_log.rb:

class SpecialLog
  LogFile = Rails.root.join('log', 'special.log')
  class << self
    cattr_accessor :logger
    delegate :debug, :info, :warn, :error, :fatal, :to => :logger
  end
end

initialize the logger in (say) config/initializers/special_log.rb:

SpecialLog.logger = Logger.new(SpecialLog::LogFile)
SpecialLog.logger.level = 'debug' # could be debug, info, warn, error or fatal

Anywhere in your app, you can log with:

SpecialLog.debug("something went wrong")
# or
SpecialLog.info("life is good")