Git Product home page Git Product logo

sniffer's Introduction

Sniffer

Build Gem Version Join the chat at https://gitter.im/aderyabin/sniffer

Sniffer aims to help:

  • Log outgoing HTTP requests. Sniffer logs as JSON format for export to ELK, Logentries and etc.
  • Debug requests. Sniffer allows to save all requests/responses in storage for future debugging

Sniffer supports most common HTTP accessing libraries:

Demo

demo

Installation

Add this line to your application's Gemfile:

gem 'sniffer'

If you wish Sniffer to use Module#prepend instead of alias_method, you can cause individual adapters to use prepend instead with:

gem 'sniffer', require: ['http_prepend', 'httpclient_prepend', 'sniffer']

It's important that 'sniffer' is the last item in the list. See the lib directory for a list of prependable adapters.

If you want all adapters to use prepend:

gem 'sniffer', require: ['all_prepend', 'sniffer']

And then execute:

$ bundle

Or install it yourself as:

$ gem install sniffer

Usage

Here's some simple examples to get you started:

require 'http'
require 'sniffer'

Sniffer.enable!

HTTP.get('http://example.com/?lang=ruby&author=matz')
Sniffer.data[0].to_h
# => {:request=>
#   {:host=>"example.com",
#    :query=>"/?lang=ruby&author=matz",
#    :port=>80,
#    :headers=>{"Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "Connection"=>"close"},
#    :body=>"",
#    :method=>:get},
#  :response=>
#   {:status=>200,
#    :headers=>
#     {"Content-Encoding"=>"gzip",
#      "Cache-Control"=>"max-age=604800",
#      "Content-Type"=>"text/html",
#      "Date"=>"Thu, 26 Oct 2017 13:47:00 GMT",
#      "Etag"=>"\"359670651+gzip\"",
#      "Expires"=>"Thu, 02 Nov 2017 13:47:00 GMT",
#      "Last-Modified"=>"Fri, 09 Aug 2013 23:54:35 GMT",
#      "Server"=>"ECS (lga/1372)",
#      "Vary"=>"Accept-Encoding",
#      "X-Cache"=>"HIT",
#      "Content-Length"=>"606",
#      "Connection"=>"close"},
#    :body=> "OK",
#    :timing=>0.23753299983218312}}

You can clear saved data

Sniffer.clear!

You can configure capacity of storage to prevent the huge memory usage and set up log rotation. By default log rotation is active (when capacity is set) and log works like a queue. If rotation is disabled - requests will be logged until result log size reaches the capacity.

# will fill the storage and stop logging
Sniffer.config.store = {capacity: 1000, rotate: false}

# will rotate logs to fit 1000 results (rotate is true by default)
Sniffer.config.store = {capacity: 1000}

You can reset config to default

Sniffer.reset!

You can enable and disable Sniffer

Sniffer.enable!
Sniffer.disable!

By default output log looks like that:

D, [2017-10-26T16:47:14.007152 #59511] DEBUG -- : {"port":80,"host":"example.com","query":"/?lang=ruby&author=matz","rq_connection":"close","method":"get","request_body":"","status":200,"rs_accept_ranges":"bytes","rs_cache_control":"max-age=604800","rs_content_type":"text/html","rs_date":"Thu, 26 Oct 2017 13:47:13 GMT","rs_etag":"\"359670651+gzip\"","rs_expires":"Thu, 02 Nov 2017 13:47:13 GMT","rs_last_modified":"Fri, 09 Aug 2013 23:54:35 GMT","rs_server":"ECS (lga/1385)","rs_vary":"Accept-Encoding","rs_x_cache":"HIT","rs_content_length":"1270","rs_connection":"close","timing":0.513012999901548,"response_body":"OK"}

where rq_xxx is request header and rs_xxx - response header

Configuration

Sniffer default options:

Sniffer.config do |c|
  c.logger = Logger.new($stdout)
  c.severity = Logger::Severity::DEBUG
  # HTTP options to log
  c.log = {
    request_url: true,
    request_headers: true,
    request_body: true,
    request_method: true,
    response_status: true,
    response_headers: true,
    response_body: true,
    timing: true
  }
  c.store =  true # save requests/responses to Sniffer.data
  c.enabled = false  # Sniffer disabled by default
  c.url_whitelist = nil
  c.url_blacklist = nil
end

Whitelist

You can add specific host url to whitelist as regexp or string. Sniffer will store only requests that matched.

Sniffer.config.url_whitelist = /whitelisted.com/

HTTP.get('http://example.com')
Sniffer.data[0].to_h
# => {}

HTTP.get('http://whitelisted.com/')
Sniffer.data[0].to_h
# => {{:request=>{:host=>"whitelisted.com", ....}}

Blacklist

You can add specific host url to blacklist as regexp or string. Sniffer will ignore all matched requests.

Sniffer.config.url_blacklist = /blacklisted.com/

HTTP.get('http://blacklisted.com')
Sniffer.data[0].to_h
# => {}

HTTP.get('http://example.com')
Sniffer.data[0].to_h
# => {{:request=>{:host=>"example.com", ...}}

Middleware

You can add the middleware to run custom code before/after the sniffed data was logged.

Sniffer.middleware do |chain|
  chain.add MyHook
end

class MyHook
  def request(data_item)
    puts "Before work"
    yield
    puts "After work"
  end

  def response(data_item)
    puts "Before work"
    yield
    puts "After work"
  end
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Development (with Docker)

Get local development environment working and tests running is very easy with docker-compose:

docker-compose run app bundle
docker-compose run app bundle exec rspec

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/aderyabin/sniffer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

Acknowledge

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Sniffer project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

sniffer's People

Contributors

aderyabin avatar dissident avatar dsalahutdinov avatar gitter-badger avatar kenta-s avatar mimikadze avatar moofkit avatar nate-at-gusto avatar palkan avatar russo-matrosso avatar sclinede avatar sponomarev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sniffer's Issues

Add white/black lists

Add whitelist/blacklist url template support

Sniffer.config do |c|
  c.url_whitelist = /api.github.com/
end

# or
Sniffer.config do |c|
  c.url_blacklist= /localhost:6379/
end

Remove dependency on `active_attr`

Is your feature request related to a problem? Please describe.

Upon examining our dependencies, I noticed that sniffer pulls in a lot of dependencies that we do not use, and do not want to bring into our Hanami app.

    active_attr (0.15.1)
      actionpack (>= 3.0.2, < 6.2)
      activemodel (>= 3.0.2, < 6.2)
      activesupport (>= 3.0.2, < 6.2)

Describe the solution you'd like

Would it be possible to implement this gem without depending on the active* gems? To be more friendly to the non-rails ecosystem, something like dry-struct could be used, although not required.

HTTP with streaming error

When using http gem the following code fail:

res = get(uri)
body = res.body
while (s = body.readpartial)
  io << s
end
io

When Sniffer is enabled it raises body has already been consumed.

The body is consumed when to_s is called here.

Broken support of EventMachine

When I'm trying to use Sniffer with Thin - I'm failing on Rails server start with Runtime Error.

Problem happens with the string EventMachine::HttpClient.send(:include, Sniffer::Adapters::EventMachineAdapter::Client) if defined?(::EventMachine).
When you use Thin - EventMachine is defined, but EventMachine::HttpClient is implemented in separate gem called em-http-request.

Do you want me to change the EvenMachineAdapter (to verify that EventMachine::HttpClient is defined) , or you could fix in other "right" way?

Demo speed

Great gem, it looks very useful!

It's a pity that the demo's speed is too fast. It is impossible (at least for me) to pick up the usage examples.

Do you think you could include the examples in the README? They really look very interesting!

Custom data store

Hi, I'm looking to implement the following for a Rails app: I'd like to store all requests/responses that happen within an app request. That way, if there are any errors that happen during the app request, I can take all the sniffer data and attach it to my bug reporting service.

This is currently technically doable, but the data store is not thread-safe. It would be cool if we can configure our own @data store if there's no plans to improve the current one.

Ruby 2.7 deprecation warnings (Anyway Config gem dependency)

Sniffer 0.4.0 has a dependency spec.add_dependency "anyway_config", ">= 1.0". Which raises multiple deprecation warnings in Ruby 2.7.

It looks like these have been fixed but you'd need to bump >=2.0 which means dropping support for Ruby < 2.5.

Request specific middleware parameters

Use case

What I'm trying to accomplish is store all outgoing request/responses in the DB with a context on this request. I want to be able to, for example, store the logged in user to the database alongside the payload & response body. My current implementation is that I added a middleware class that implements the request & response methods.

Alternative approach

  1. Manually store each request to be able to add any additional parameters
  2. Generate a UID for each request that can be later used

Any alternative approaches or ideas?

Thank you for this great gem

stack level too deep

sniffer patches net-http with alias_method. This causes problems when other gems (rack-mini-profiler, APMs like datadog) use prepend to patch the same methods, leading to stack level too deep.

See: palkan/isolator#44

Add block usage

Add isolated usage support

sniffer = Sniffer.new do 
# some code here
end

sniffer.data

Setting store to false prevents logging

What did you do?

Set Sniffer.store = false

What did you expect to happen?

I expected Sniffer.data not to get populated, but I expected the logging to still occur.

What actually happened?

When store was set to false, logging did not occur.

Additional context

It seems like the middleware implementation of logging does not get called if store is disabled.

Environment

Ruby Version:
2.7

Framework Version (Rails, whatever):
Rails 6.0.2.2

Sniffer Version:
0.4.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.