Gerry Shaw
Gerry Shaw

Reputation: 9378

How to prevent logging Rails stack trace

I'm trying to reduce the amount of noise in my logs and would like to disable Rails from logging the stack trace during errors.

Since I am using an error reporting service (Honeybadger.io) I don't need to see the stack trace in the logs as it's already available in the exception report from the error handling service.

Upvotes: 5

Views: 2760

Answers (3)

ejoubaud
ejoubaud

Reputation: 5241

The default Rails middleware DebugExceptions is what logs the errors.

You can remove it with config.middleware.delete(ActionDispatch::DebugExceptions) in your config/environment.rb or config/environments/production.rb

Upvotes: 3

Mikhail Chuprynski
Mikhail Chuprynski

Reputation: 2493

Well, Rails.backtrace_cleaner.add_silencer works, but I woulnd call its behaviour predictable

https://github.com/vipulnsward/rails/blob/ecc8f283cfc1b002b5141c527a827e74b770f2f0/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L155-L156

Since application_trace is empty(This is because error is not from user code but route error), we are falling back to framework_trace, which does not filter it (it filters only noise).

You can solve it with creating your own log_formatter. In your development.rb and/or test.rb add

config.log_formatter = SilentLogger.new
config.log_formatter.add_silencer { |line| line =~ /lib/ }

And create simple class in models with only method call required. There you can modify your backtrace as you wish.

class SilentLogger
  def initialize
    @silencers = []
  end

  def add_silencer(&block)
    @silencers << block
  end

  def call(severity, timestamp, progname, msg)
    backtrace = (String === msg) ? "#{msg}\n" : "#{msg.inspect}\n"

    return backtrace if @silencers.empty?

    @silencers.each do |s|
      backtrace = backtrace.split("\n").delete_if { |line| s.call(line) }
    end

    backtrace.join("\n")
  end
end

Upvotes: 0

Gerry Shaw
Gerry Shaw

Reputation: 9378

According to the docs you should be able to add a backtrace silencer that excludes every line by returning true in the block.

But, at least with Rails 4.2.5.2, this doesn't appear to be working and even if it did work you would still end up with a line in log about the exception.

Accidentally I discovered that if you raise an error inside a silencer block that this will suppress the error message and the entire backtrace which turns out to be exactly what I'm looking for.

Rails.backtrace_cleaner.add_silencer { |_line| raise }

Combining this hack with the concise_logging gem I can now have logs that look like the following:

enter image description here

Upvotes: 1

Related Questions