Ole Spaarmann
Ole Spaarmann

Reputation: 16749

Rails: How to write to a custom log file from within a rake task in production mode?

I'm trying to write to my log files while running a rake task. It works fine in development mode, but as soon as I switch to the production environment, nothing is written to the log files.

I read here

How do I use a custom log for my rake tasks in Ruby on Rails?

that this is the normal behavior and also found a #wontfix ticket in lighthouse.

My question: Is there a way to output, what's going on while my rake task is running? It performs some crawling and runs for hours. I would prefer if the output went in a specific log file like /log/crawler.log

Right now I'm just using this command to write to the log files:

ActiveRecord::Base.logger.info "Log Text"

Thanks!

Upvotes: 8

Views: 14093

Answers (3)

ikko karima
ikko karima

Reputation: 21

Maybe you need to write out the buffer where you need it:

logger.flush

or you can turn on auto flushing:

task :foo => :environment do
  Rails.logger.auto_flushing = 1
  Rails.logger.info "bar"
end

Upvotes: 2

jspooner
jspooner

Reputation: 11315

You can make a new logger with Logger.new("file.log") and then call it's methods like this.

  task :import_stuff => :environment do
    require 'csv'
    l = Logger.new("stuff.log")
    csv_file = "#{RAILS_ROOT}/stuff.csv"
    CSV.open(csv_file, 'r') do |row|
      l.info row[1]
     end
  end

Upvotes: 3

Daniel Beardsley
Daniel Beardsley

Reputation: 20367

The problem you are having is that rails ignores 'info' level logs in production mode.

I'd recommend reading this: http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/classes/Logger.html

and creating your own logger:

logger = Logger.new('logfile.log')
logger.info "Something happened"

Upvotes: 15

Related Questions