Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log specific request details to rails server logs

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 accomplishing this.

Basically, I need to capture the following information for each request in a single log statement (if possible)

  • Date of log entry
  • Time of log entry
  • HTTP method
  • URL requested
  • Port
  • IP address of requestor
  • User agent of the requestor
  • Referring URL
  • HTTP response code
  • Hostname

    What's the preferred way of customizing the log format? Is it possible to just modify the existing logs and pass it this information? Or would I need to extend and overwrite the behavior I need?

    I don't need this to be saved to a different log file or anything, just output to STDOUT on each request.

    Any help with this would be greatly appreciated.

    Thanks!

  • like image 718
    Craig Kochis Avatar asked Jun 29 '12 19:06

    Craig Kochis


    2 Answers

    I know this is an old question, but for future people that stumble upon this, I believe the preferred approach in Rails 3.2+ would be to use ActiveSupport::TaggedLogging. The blog post introducing this is here

    And a quick example that adds the subdomain, a UUID per request, and the user agent to each log message. You can pop this in your environment initialization file.

    config.log_tags = [ :subdomain, :uuid, lambda { |request| request.user_agent } ]
    
    like image 130
    cassanego Avatar answered Oct 01 '22 12:10

    cassanego


    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
    like image 32
    mmrobins Avatar answered Oct 01 '22 13:10

    mmrobins