How do I see the whole HTTP request in Rails

后端 未结 4 701
北海茫月
北海茫月 2020-12-29 04:20

I have a Rails application but after some time of development/debugging I realized that it would be very helpful to be able to see the whole HTTP request in the logfiles - l

相关标签:
4条回答
  • 2020-12-29 04:55

    You can rapidly see the request.env in a view via:

    • VIEW: <%= request.env.inspect %>

    If instead you want to log it in development log, from your controller:

    • CONTROLLER: Rails.logger.info(request.env)

    Here you can see a reference for the Request object.

    Rails automatically sets up logging to a file in the log/ directory using Logger from the Ruby Standard Library. The logfile will be named corresponding to your environment, e.g. log/development.log.

    To log a message from either a controller or a model, access the Rails logger instance with the logger method:

    class YourController < ActionController::Base
      def index
        logger.info request.env
      end
    end
    

    About the user, what are you using to authenticate It?

    0 讨论(0)
  • 2020-12-29 04:58

    That logger.info request.env code works fine in a Rails controller, but to see a more original version of that, or if you're using Grape or some other mounted app, you have to intercept the request on its way through the rack middleware chain...

    Put this code in your lib directory (or at the bottom of application.rb):

    require 'pp'
    class Loggo
      def initialize(app)
        @app = app
      end
      def call(env)
        pp env
        @app.call(env)
      end
    end
    

    then in with the other configs in application.rb:

    config.middleware.use "Loggo"
    
    0 讨论(0)
  • 2020-12-29 04:59

    I've initially used the code snippet by @AlexChaffee, but I've since switched to using mitmproxy, a specialized HTTP proxy that records the requests and responses passing through it.

    This is obviously only helpful for development scenarios when you control the applications making the requests. You might be able to achieve similar results with a reverse proxy for production applications (the advantage being that you don't have to touch the Rails application itself for this), but I haven't looked into this.

    0 讨论(0)
  • 2020-12-29 05:04

    You can use rack middleware to log the requests as the middleware sees them (as parsed by the http-server and as transformed by preceding middleware). You can also configure your http-server to log full requests, if your http-server supports such a feature.

    The http-server (web-server) is responsible for receiving http requests, parsing them, and transmitting data structures to the application-server (e.g., a rack application). The application-server does not see the original request, but sees what the http-server sends its way.

    0 讨论(0)
提交回复
热议问题