Question: Logging raw SQL errors in Rake Tasks

Question

Logging raw SQL errors in Rake Tasks

Answers 1
Added at 2016-12-22 16:12
Tags
Question

I'm using raw sql bulk updates (for performance reasons) in the context of a rake task. Something like the following:

update_sql = Book.connection.execute("UPDATE books AS b SET
             stock = vs.stock,
             promotion = vs.promotion,
             sales = vs.sales
             FROM (values #{values_string}) AS vs
             (stock, promotion, sales) WHERE b.id = vs.id;")

While everything is "transparent" in local development, if this SQL fails in production during the execution of the rails task (for example because the promotion column is nil and the statement becomes invalid), no error is logged.

I can manually log this with catching the exception, like below, however some option that would allow for automatic logging would be better.

begin
...
rescue ActiveRecord::StatementInvalid => e
        Rails.logger.fatal "Books update: ActiveRecord::StatementInvalid: "+ e.to_s
end
Answers to

Logging raw SQL errors in Rake Tasks

nr: #1 dodano: 2016-12-22 22:12

You can make your own custom class in your model folder: app/models/custom_sql_logger.rb :

class CustomSqlLogger
  def self.debug(msg=nil)
    @custom_log ||= Logger.new("#{Rails.root}/log/custom_sql.log")
    @custom_log.debug(msg) unless msg.nil?
  end
end

Then go to the rake task where you would like to debug updated fields for example lib/task/calculate_avarages.rake and call your custom debugger:

CustomSqlLogger.debug "The field was successfully updated into DB"

Example from my project:

require 'rake'

task :calculate_averages => :environment do
  products = Product.all

      products.each do |product|
        puts "Calculating average rating for #{product.name}..."
        product.update_attribute(:average_rating, product.reviews.average("rating"))

        CustomSqlLogger.debug "#{product.name} was susscefully updated into DB"

      end
    end

Custom debugger will create the new file custom_sql.log into log folder: log/custom_sql.log and saved all information there. Beware of a log file size after a while.

Source Show
◀ Wstecz