Include params/request information in Rails logger?

前端 未结 3 1314
失恋的感觉
失恋的感觉 2020-12-24 08:51

I\'m trying to get some more information into my Rails logs, specifically the requested URI or current params, if available (and I appreciate that they won\'t always be). Ho

相关标签:
3条回答
  • 2020-12-24 08:55

    (Responding a long time after this was asked, but maybe it will help the next person.)

    I just did something similar.

    1) you need to override your logger separately from logging request-leve details. Looks like you've figured customizing your logger out. Answer is here: Rails logger format string configuration

    2) I log the request and response of all requests into my service. Note, that Rails puts a tonne of stuff into the headers, so just straight dumping the request or the headers is probably a bad idea. Also of note, my application is primarily accessed via an API. If yours is primarily a web-app, as I'm guessing most people's are, you probably don't want to inspect the response.body as it will contain your html.

    class ApplicationController < ActionController::Base 
      around_filter :global_request_logging
    ...
      def global_request_logging 
        http_request_header_keys = request.headers.keys.select{|header_name| header_name.match("^HTTP.*")}
        http_request_headers = request.headers.select{|header_name, header_value| http_request_header_keys.index(header_name)}
        logger.info "Received #{request.method.inspect} to #{request.url.inspect} from #{request.remote_ip.inspect}.  Processing with headers #{http_request_headers.inspect} and params #{params.inspect}"
        begin 
          yield 
        ensure 
          logger.info "Responding with #{response.status.inspect} => #{response.body.inspect}"
        end 
      end 
    end
    
    0 讨论(0)
  • 2020-12-24 08:59

    This should work! :) cheers.

    logger.info({:user_agent => request.user_agent, :remote_ip => request.remote_ip}.inspect)

    logger.info(params.inspect)

    By the by.. This should be placed in your controllers action. Ex: If you place it in your create action it should also log the user_agent i.e the browser, remote_ip i.e the remote ip of the user and all the params.

    0 讨论(0)
  • 2020-12-24 09:09

    you should look in the request class

    like puts request.uri.

    check here for more detail http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html

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