Search code examples
ruby-on-railsloggingconditional-statementsproduction-environment

Rails - conditionally log for a specific hostname


I'm looking for a way to configure a Rails server log only if the client has contacted a specific hostname. e.g. I could make it so that http://public.example.com doesn't get logged, but http://debug.example.com (same underlying Rails app server) does get logged (or ideally gets logged in more detail than the regular host). It would help with production debugging.


Solution

  • You can use gem Lograge to customize your log. This gem will give you much more custom to your log. For example, in your case, I will do this

    After install the gem. Create a file at config/initializers/lograge.rb

    # config/initializers/lograge.rb
    Rails.application.configure do
      config.lograge.enabled = true
    
      config.lograge.custom_options = lambda do |event|
        # custom log on specific domain
        if event.payload[:host] == "debug.example.com"
          {:host => event.payload[:host]}
        else
          {}
        end
      end
    end
    

    And in your Application Controller

    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
    
      # This will add request's host to lograge so you can use it to filter log later
      def append_info_to_payload(payload)
        super
        payload[:host] = request.host
      end
    end
    

    Now you can customize your log base on domain, on how to customize it please read at: https://github.com/roidrage/lograge