Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails log model errors on failed save

How I can log to a file validation errors of models ?

I want to have a custom log file, where validation errors are logged when I play in development mode with my application.

What is the best option to achieve that ?

Is monkey patching of the save method a good idea ? Or have You some better way to do that ?

like image 672
astropanic Avatar asked Jan 13 '11 10:01

astropanic


3 Answers

Depends on what you want to do but how about something like this:

# model
after_validation :log_errors, :if => Proc.new {|m| m.errors}

def log_errors
  Rails.logger.debug self.errors.full_messages.join("\n")
end
like image 156
Lenart Avatar answered Oct 31 '22 19:10

Lenart


I've combined both of Lenart and Altonymous suggestions. So we make a concern (since Rails 4)

# app/models/concerns/log_validation_errors.rb
module LogValidationErrors
  extend ActiveSupport::Concern

  included do
    after_validation :log_errors, if: proc { |m| m.errors }
  end

  def log_errors
    Rails.logger.debug "Validation failed!\n" + errors.full_messages.map { |i| " - #{i}" }.join("\n")
  end
end

and change our models to include it

# app/models/my_model.rb
class MyModel < ApplicationRecord
  include LogValidationErrors
  # ...
end
like image 44
dhilt Avatar answered Oct 31 '22 19:10

dhilt


I know this is old... but for others. I created a module that I include in my models.

# validation_logger.rb
module ValidationLogger
  def self.included(base)
    base.send :include, InstanceMethods

    base.after_validation :log_errors, if: ->(m) { m.errors.present? }
  end

  module InstanceMethods
    def log_errors
      Rails.logger.warn "#{self.class.name} #{self.id || '(new)'} is invalid: #{self.errors.full_messages.inspect}"
    end
  end
end
like image 22
Altonymous Avatar answered Oct 31 '22 20:10

Altonymous