Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using rails logger in rake tasks, rails 5

Tags:

I'm building a ruby on rails app, using rails 5, and I have a number of rake tasks from which I'd like to log information. However, when I attempt to access the logger, I get an error: undefined local variable or method `logger'

I have my rake tasks in lib/tasks, and I've declared a logger in both production.rb and developement.rb

Here's an example task:

namespace :some_namespace do
    desc "a description"
    task :scrape_info do
        include Scraper
        startTime = Time.now
        Rails.logger.tagged("Scraper") { Rails.logger.info "Beginning scrape: #{startTime} " }
        Scraper.scrape_info
        endTime = Time.now
        Rails.logger.tagged("Scraper") { Rails.logger.info "Finished scrape: #{endTime} " }
    end
end

And an excerpt from development.rb where I have the logger defined:

 config.logger = Logger.new(STDOUT)
 config.log_level = :info
 config.logger = ActiveSupport::TaggedLogging.new(logger)

Any idea how to incorporate the logger into rake tasks? I understand that I could simply use a puts statement to print to stdout, but eventually I'd like to have daily log files, and I would like my rake tasks to be included in those files

ANSWER: Simply add the environment tag given in the answer from @Joel_Blum. Also, in development.rb, the line

config.logger = ActiveSupport::TaggedLogging.new(logger)

needs to be:

config.logger = ActiveSupport::TaggedLogging.new(config.logger)
like image 283
Nathan Lauer Avatar asked Dec 19 '16 16:12

Nathan Lauer


1 Answers

Try adding the environment, this will have the effect of loading your rails app.

 task :scrape_info => :environment do
  ...
 end
like image 166
Joel Blum Avatar answered Sep 22 '22 17:09

Joel Blum