Samuel

Samuel is a gem for automatic logging of your Net::HTTP requests. It’s named for the serial diarist Mr. Pepys, who was known to reliably record events both quotidian and remarkable.

Should a Great Plague, Fire, or Whale befall an important external web service you use, you’ll be sure to have a tidy record of it.

Usage:

When Rails is loaded, Samuel configures a few things automatically. So all you need to do is this:

# config/environment.rb
config.gem "samuel"

And Samuel will automatically use Rails’s logger and an ActiveRecord-like format.

For non-Rails projects, you’ll have to manually configure logging, like this:

require 'samuel'
Samuel.logger = Logger.new('http_requests.log')

If you don’t assign a logger, Samuel will configure a default logger on STDOUT.

Configuration

There are two ways to specify configuration options for Samuel: global and inline. Global configs look like this:

Samuel.config[:labels]          = {"example.com" => "Example API"}
Samuel.config[:filtered_params] = :password

You should put global configuration somewhere early-on in your program. If you’re using Rails, config/initializers/samuel.rb will do the trick.

Alternatively, an inline configuration block temporarily overrides any global configuration for a set of HTTP requests:

Samuel.with_config :label => "Twitter API" do
  Net::HTTP.start("twitter.com") { |http| http.get("/help/test") }
end

Right now, there are three configuration changes you can make in either style:

  • :labels - This is a hash with domain substrings as keys and log labels as values. If a request domain includes one of the domain substrings, the corresponding label will be used for the first part of that log entry. By default this is set to \{"" => "HTTP"}, so that all requests are labeled with "HTTP Request".

  • :label - As an alternative to the :labels hash, this is simply a string. If set, it takes precedence over any :labels (by default, it’s not set). It gets "Request" appended to it as well – so if you want your log to always say Twitter API Request instead of the default HTTP Request, you can set this to "Twitter API". I’d recommend using this setting globally if you’re only making requests to one service, or inline if you just need to temporarily override the global :labels.

  • :filtered_params - This works just like Rails’s filter_parameter_logging method. Set it to a symbol, string, or array of them, and Samuel will filter the value of query parameters that have any of these patterns as a substring by replacing the value with [FILTERED] in your logs. By default, no filtering is enabled.

Samuel logs successful HTTP requests at the INFO level; Failed requests log at the WARN level. This isn’t currently configurable, but it’s on the list.

License

Copyright 2009 Chris Kampmeier. See LICENSE for details.