Question: Logging raw SQL errors in Rake Tasks


Logging raw SQL errors in Rake Tasks

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

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 =;")

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.

rescue ActiveRecord::StatementInvalid => e
        Rails.logger.fatal "Books update: ActiveRecord::StatementInvalid: "+ e.to_s
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 ||="#{Rails.root}/log/custom_sql.log")
    @custom_log.debug(msg) unless msg.nil?

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 #{}..."

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


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