开发者

How do I redirect the sql statements in Rails to other than log/development.log?

开发者 https://www.devze.com 2023-04-10 23:52 出处:网络
Something in Rails (ActiveRecord::Base.logger ?) puts all executed SQL into log/development.log. I have a rails app, whose data is populated by several rake tasks. Often in development, I want to run

Something in Rails (ActiveRecord::Base.logger ?) puts all executed SQL into log/development.log.

I have a rails app, whose data is populated by several rake tasks. Often in development, I want to run the web app, and run several of these rake tasks simultaneously (they are long running tasks that talk to other systems and create data in a lo开发者_如何学Pythoncal database).

Annoyingly, they all log to the same file at the same time.

How/where should I change this? Can I do it from the command line? Where (if in a rake file) should I do it? Or should I create new environments for each rake task?

Is there documentation i should have read to answer this, where is it?

Thanks a bunch.


Depends on what you are really trying to log. In Rails 3.+ you can use the ActiveSupport::LogSubscriber mechanism to hook into Rails internals and log certain interests to other files.

If you really want to hijack the core Rails.logger instance for each of your rake tasks, than do just that.

  # lib/tasks/foo.rake

  desc "Prints Hello World"
  task :helloworld do
     Rails.logger = Logger.new("/path/to/hello-world.log")
     # do something in your Rails stack that would write to "Rails.logger"
  end

Not tested, but I think that might work.

That being said, I think subscribing to interesting events in ActiveRecord via ActiveSupport::LogSubscriber might be a cleaner approach


My current solution is

dec "update statistics"
task :update_stats => :environment do

     root_path = Rails.configuration.root_path
     env = Rails.configuration.environment
     ActiveRecord::Base.logger = Logger.new(File.join(root_path, "log", "#{env}-stats.log"))
     #code ...

end

It feels a bit hacky, but maybe that's just the way to do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号