How do I use a custom log for my rake tasks in Rub

2019-06-07 14:11发布

问题:

I have a rake task that calls functions like this:

namespace :blah do
    task :hello_world => :environment do
       logger.info("Hello World")
       helloworld2
    end
end

def helloworld2
   logger.info("Hello Again, World")
end

I want the log output to a custom log, and I really don't want to have to pass a log reference every time I make a function call. I found this somewhere (can't find it again):

def logger
  @@logger ||= Logger.new("#{RAILS_HOME}/log/blah.log")
end

But this does not work for me and I am not sure what it even does because I grabbed the code a long time ago and haven't used it until now. I can't search for @@ on google (tried +"@@" rails) to see what it does. Any help on this issue would be great. I am hoping for a quick solution and not having to install a gem or plugin (unless there is a really really good reason to.

Thanks!

回答1:

rake disables logging in production mode. make sure you're running in development mode if you want it to log



回答2:

  1. What do you mean by "does not work for me"? I just tried this same code and it worked - created a new log file and put some text in it.
  2. @@logger is a class variable, it's a language issue, not Rails' one. I believe there's no need in further explanations :)
  3. You've probably mistaken typing "function helloworld2" :)


回答3:

Advanced Rails Recipes Recipe 84 from @topfunky shows how to define a custom logger. He has some code in the environment config file (production would look like this): RAILS_ROOT/config/environments/production.rb:

config.logger = RAILS_DEFAULT_LOGGER = Logger.new(config.log_path)

I'd test that out instead of redefining the class variable as you have. He might have something on http://nubyonrails.com to check as well.