How to log specific request details to rails server logs

前端 未结 2 599
自闭症患者
自闭症患者 2021-02-07 20:13

I typically don\'t like to ask directly how to do something without much understanding of what\'s going on, but I\'m fairly new to rails and I\'m having a hard time accomplishin

2条回答
  •  遥遥无期
    2021-02-07 20:43

    I believe most, if not all, of the info you requested can be found in the request headers and response. Information on how to add that to logs has been answered before, but basically you can use an around_filter in the ApplicationController to log the information you care about form the request headers. For example here's how you could log the user agent from the request and status code from the response:

    class ApplicationController < ActionController::Base 
      around_filter :global_request_logging
    
      def global_request_logging 
        logger.info "USERAGENT: #{request.headers['HTTP_USER_AGENT']}"
        begin 
          yield 
        ensure 
          logger.info "response_status: #{response.status}"
        end 
      end 
    end
    

    As far as getting the format you want, if you wrap calls you can output whatever format you want. Also, the Rails logger is also very customizable, and a few projects already exist that might suit your needs to replace default logging or as inspiration for how to go about creating a useful format:

    • lograge - replaces default Rails logging with single line, key-value output, but doesn't yet do request parameters
    • scrolls - More generic contextual, key-value

提交回复
热议问题