Rails 3 - log all requests

I have an application that makes many API calls (xml and json). We want to register our response to all requests (we will filter our html answers).

In general, we receive calls in REST and return JSON or XML. I register them today with round_filter in the application controller to let me:

class ApplicationController < ActionController::Base around_filter :global_request_logging def global_request_logging # log request begin yield ensure #log response end end rescue_from Exception do |exception| respond_to do |format| format.xml {head 400} # etc for JSON and HTML end end end 

The problem I am facing is that when I register the response, we have not yet deleted the rescue_from block, so we register that we are returning 200.

This leads me to believe that there is a better way / place to register a request / response in Rails. Ideally, I am looking for a way to register the wire - as raw materials, as inputs and outputs from the client.

+4
source share
1 answer

You can use Rack middleware, for example:

 module Rack class Snoop def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) case status when 200 # Who needs weekly status reports? mail(:to => " myteamleader@mycompany.com ", :subject => "See, I told you the application works!", :body => body) when 500 # A bit of extra motivation to fix these errors mail(:to => " ceo@mycompany.com ", :subject => "Look boss, the application is broken again!", :body => body) end [status, headers, body] end end end 

You can use it by placing it in your config/application.rb or in one of config/environments/ENV.rb

 config.middleware.insert_before(ActionDispatch::ShowExceptions, Rack::Snoop) 

You will notice that I inserted it before ActionDispatch::ShowExceptions , because it will catch 500 errors caused by internal exceptions. If you want it elsewhere, you can peek into the middleware stack with rake middleware and put it wherever you want with insert_before or insert_after .

+3
source

All Articles