简体   繁体   中英

Rails - Error log backtrace as a JSON

I have converted my logs output to JSON in production using lograge, it makes it easier to display on several log services like Amazon.

config.lograge.enabled = true
  config.lograge.formatter = Lograge::Formatters::Logstash.new

  # add time to lograge
  config.lograge.custom_options = lambda do |event|
    params = event.payload[:params].reject { |k| %w(controller action).include?(k) }
    {
      time: event.time,
      params: params
    }
  end

However, when an error occurs the error backtrace is also logged, but not as a JSON, instead as a normal string (and one line per backtrace entry =_=). This creates a lot of unwanted lines (example on Amazon CLoudwatch : )

F, [2016-11-12T18:08:09.774760 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9] SomeModule::SomeError (error explanation):

18:08:09
F, [2016-11-12T18:08:09.774790 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9]
i-xxx
F, [2016-11-12T18:08:09.774790 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9]

18:08:09
F, [2016-11-12T18:08:09.774813 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9] actionpack (5.0.0.1) lib/some_module.rb:53:in `call'
i-xxxxx
F, [2016-11-12T18:08:09.774813 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9] actionpack (5.0.0.1) lib/some_module.rb:53:in `call'

18:08:09
F, [2016-11-12T18:08:09.774834 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9] actionpack (5.0.0.1) lib/some_module.rb:31:in `call'
i-xxxxx
F, [2016-11-12T18:08:09.774834 #15892] FATAL -- : [2f480b01-d8fa-459c-97dd-a904c98cfce9] actionpack (5.0.0.1) lib/some_module.rb:31:in `call'

Instead, I'd like to condense all this backtrace into a single json log that would look like

{
  error: 'SomeModule::SomeError (error explanation)',
  backtrace: [
    'some_gem (5.x) lib/some_module.rb:53:in `call', 
    'some_gem (5.x) lib/some_module.rb:31:in `call', ...]
} 

How can I do that in addition to lograge json formatting for requests without errors ?

You want to add a new route to catch all RoutingError exceptions. The lograge readme does a good job of explaining what to do ( https://github.com/roidrage/lograge ). In a nutshell, you need a route that catches "all", ie get '*unmatched_route', to: 'application#route_not_found' and have that route to a 404, rather than firing an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM