21

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 ?

4 Answers 4

31

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
Sign up to request clarification or add additional context in comments.

Comments

12

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

Comments

3

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

Comments

1

I would write a before_save callback and log the errors if valid? returns false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.