Question

I am trying to disable logging of IP addresses while handling the request. But I am not able find a way to do this. I want to disable logging of IP for limited portion of my app where user is not yet authenticated.

So my questions is

How to disable logging of IP in rails log for specific pages(so the IP will not be saved in any log)

I am using Rails 3.2.17

EDIT: Here is sample log (from environment.log)

Started GET "/my_path" for 192.168.0.109 at 2014-03-28 11:53:20 +0530

I do not want to save 192.168.0.109 in log file

Was it helpful?

Solution 2

Finally did this by using emaillenin's answer thanx emaillenin :D.

Here is solution

  # Overriding Rails logger to not save IP addresses for specific paths
  # Put this file in <app_root>/config/initializers

  # defining setter for Rails default log formatter, so later we can set our custom logger using '='
  class ActiveSupport::BufferedLogger
    def formatter=(formatter)
      @log.formatter = formatter
    end
  end

  # Modified Formatter Class with custom 'call' method
  class Formatter
    Format = "%s\n"
    # Remove IP while getting request on below specified Path
    FilteredActionRegexp = /app_path|another_path/i

    # reference for regexp of IP address
    # http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/
    IPRegexp = /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/
    FilteredString = '**FILTERED**'

    def call(severity, time, progname, msg)
      Format % [msg2str(filter_ip(msg))]
    end

    private

    def msg2str(msg)
      case msg
      when ::String
        msg
      when ::Exception
        "#{ msg.message } (#{ msg.class })\n" <<
          (msg.backtrace || []).join("\n")
      else
        msg.inspect
      end
    end

    # Replace IP Address with custom string if action is filtered
    def filter_ip(msg)
      # Replace only if message contains filtered action
      if msg =~ FilteredActionRegexp
        # If log string contains IP address then remove it with custom string
        msg.gsub(IPRegexp, FilteredString )
      else
        msg
      end
    end
  end

  # Override Rails default logger formatter
  Rails.logger.formatter = Formatter.new

OTHER TIPS

In config/initializers, add file log_fomat.rb with:

class ActiveSupport::BufferedLogger
  def formatter=(formatter)
    @log.formatter = formatter
  end
end

class Formatter
  SEVERITY_TO_TAG_MAP     = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
  SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
  USE_HUMOROUS_SEVERITIES = true

  def call(severity, time, progname, msg)
    if USE_HUMOROUS_SEVERITIES
      formatted_severity = sprintf("%-3s","#{SEVERITY_TO_TAG_MAP[severity]}")
    else
      formatted_severity = sprintf("%-5s","#{severity}")
    end

    formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
    color = SEVERITY_TO_COLOR_MAP[severity]

    "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
  end

end

Rails.logger.formatter = Formatter.new

References:

  1. http://rubyjunky.com/cleaning-up-rails-4-production-logging.html
  2. http://cbpowell.wordpress.com/2012/04/05/beautiful-logging-for-ruby-on-rails-3-2/
  3. Rails logger format string configuration

I use Lograge

Taming Rails' Default Request Logging

Instead of having an unparsable amount of logging output like this:

Started GET "/" for 127.0.0.1 at 2012-03-10 14:28:14 +0100
Processing by HomeController#index as HTML
  Rendered text template within layouts/application (0.0ms)
  Rendered layouts/_assets.html.erb (2.0ms)
  Rendered layouts/_top.html.erb (2.6ms)
  Rendered layouts/_about.html.erb (0.3ms)
  Rendered layouts/_google_analytics.html.erb (0.4ms)
Completed 200 OK in 79ms (Views: 78.8ms | ActiveRecord: 0.0ms)

you get a single line with all the important information, like this:

method=GET path=/jobs/833552.json format=json controller=jobs action=show status=200 duration=58.33 view=40.43 db=15.26
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top