restash_rails 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +12 -0
  3. data/.rspec +2 -0
  4. data/.travis.yml +5 -0
  5. data/CODE_OF_CONDUCT.md +74 -0
  6. data/Gemfile +4 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +74 -0
  9. data/Rakefile +6 -0
  10. data/bin/console +14 -0
  11. data/bin/setup +8 -0
  12. data/lib/restash_rails/formatters/default.rb +19 -0
  13. data/lib/restash_rails/log_subscriber/log_subscriber.rb +24 -0
  14. data/lib/restash_rails/log_subscriber/subscribers/action_mailer.rb +23 -0
  15. data/lib/restash_rails/log_subscriber/subscribers/action_view.rb +25 -0
  16. data/lib/restash_rails/log_subscriber/subscribers/active_record.rb +22 -0
  17. data/lib/restash_rails/log_subscriber/subscribers/active_support.rb +74 -0
  18. data/lib/restash_rails/log_subscriber/subscribers/cache.rb +69 -0
  19. data/lib/restash_rails/logger.rb +93 -0
  20. data/lib/restash_rails/logs_unsubscriber.rb +47 -0
  21. data/lib/restash_rails/rails_ext/action_dispatch/middleware/debug_exceptions.rb +24 -0
  22. data/lib/restash_rails/rails_ext/action_pack/action_controller/metal/instrumentation.rb +26 -0
  23. data/lib/restash_rails/rails_ext/active_support/cache/store.rb +11 -0
  24. data/lib/restash_rails/rails_ext/core_ext/hash.rb +9 -0
  25. data/lib/restash_rails/rails_ext/rack/logger.rb +25 -0
  26. data/lib/restash_rails/railtie.rb +12 -0
  27. data/lib/restash_rails/resque/failure/restash_logger.rb +24 -0
  28. data/lib/restash_rails/resque/logging.rb +7 -0
  29. data/lib/restash_rails/resque/plugins/restash_logger.rb +38 -0
  30. data/lib/restash_rails/version.rb +3 -0
  31. data/lib/restash_rails.rb +53 -0
  32. data/restash_rails.gemspec +27 -0
  33. metadata +145 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 7f4f285f9235a1d159cb46e296d7718b29c86514
4
+ data.tar.gz: 563ec6ccee616fcea16146d1f05e04fea2725b54
5
+ SHA512:
6
+ metadata.gz: a63b259e876f4973613f3826b1742f5a07880f6e065c596a7e74571347397a2c2cdacce1bb438ff0bea56d90b4d0c0558f643a8e545557544881515446988b64
7
+ data.tar.gz: d4730a1093aa64599df276fe242cc67f0d73fe8a6b75a8c4983e21d0904b0de7918f6bb6211cc6e248783d5a3321ce1ecaf9c3964325908b0db30c4327cca51d
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .idea
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.0
5
+ before_install: gem install bundler -v 1.14.5
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at dmitri@yotpo.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in restash_rails.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Gitelzon Dmitri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # RestashRails
2
+
3
+ This gem is sending Json structured logs from your Rails app to destination you define.
4
+ We propose Logstash as a receiver. <br>
5
+ Logs sent via TCP socket with timeout, you'll define or with default of 10ms
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'restash_rails'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install restash_rails
22
+
23
+ ## Usage
24
+ Data is written to host and port you provide via configs.
25
+ We open TCP socket with timeout option you provide.
26
+ We send it in json format. So the logstash is one of the receivers you can use,
27
+ without any special config.
28
+ We also let you to path yours app custom exceptions and there statuses.
29
+ If you not, gem won't be possible to translate an exception to an appropriate status.
30
+ As a result, some responses will be logged without an exception status
31
+ Pay attention that we won't let you override Rails native exceptions statuses.
32
+
33
+ ##### In application.rb
34
+
35
+ ```ruby
36
+ #Restahs rails won't work unless you enable it
37
+ config.restash_rails.enabled = true
38
+
39
+ #If you want to leave original Rails Logs
40
+ config.restash_rails.keep_original_logs = true
41
+
42
+ #Host and port the data will be sent to
43
+ config.restash_rails.host = '127.0.0.1'
44
+ config.restash_rails.port = '9200'
45
+
46
+ #TCP Timeout options
47
+ config.restash_rails.timeout_options = {connect_timeout: DEFAULT_TIMEOUT, write_timeout: DEFAULT_TIMEOUT, read_timeout: DEFAULT_TIMEOUT}
48
+
49
+ #exception_statuses
50
+ error_401 = {:status => 401, :types => [Exceptions::AccessDenied, Exceptions::MyException]}
51
+ error_422 = {:status => 422, :types => [Exceptions::InvalidParams]}
52
+ config.exception_statuses = [error_401, error_422]
53
+ ```
54
+
55
+ All those configs can also be paassed as yaml file
56
+ ```ruby
57
+ RESTASH_RAILS_CONF = YAML::load(PATH_TO_YOUR_CONFIG_FILE)
58
+ config.restash_rails = RESTASH_RAILS_CONF[Rails.env]
59
+ ```
60
+ ## Development
61
+
62
+ 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.
63
+
64
+ 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](https://rubygems.org).
65
+
66
+ ## Contributing
67
+
68
+ Bug reports and pull requests are welcome on GitHub at https://github.com/YotpoLtd/restash-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
69
+
70
+
71
+ ## License
72
+
73
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
74
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "restash_rails"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,19 @@
1
+ module RestashRails
2
+ module Formatter
3
+ class Default
4
+ def format_message(message = nil)
5
+ log_message = {}
6
+ message.is_a?(Hash) ? log_message.merge!(message) : log_message[:log_message] = message
7
+ return log_message
8
+ rescue => e
9
+ {
10
+ severity: 'ERROR',
11
+ log_message: 'Failed to format logstash message',
12
+ exception: { class: e.class, message: e.message },
13
+ logstash_message: log_message,
14
+ log_tag: :logstash_formatter_failed
15
+ }
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,24 @@
1
+ require 'restash_rails/log_subscriber/subscribers/active_record'
2
+ require 'restash_rails/log_subscriber/subscribers/active_support'
3
+ require 'restash_rails/log_subscriber/subscribers/action_view'
4
+ require 'restash_rails/log_subscriber/subscribers/action_mailer'
5
+
6
+ module RestashRails
7
+ module LogSubscriber
8
+ def subscribe_logs(configs)
9
+ RestashRails::LogSubscriber::ActiveSupport.attach_to :action_controller
10
+ RestashRails::LogSubscriber::ActiveRecord.attach_to :active_record
11
+ RestashRails::LogSubscriber::ActionView.attach_to :action_view
12
+ RestashRails::LogSubscriber::ActionMailer.attach_to :action_mailer
13
+ require 'restash_rails/resque/logging' if is_true?(configs[:resque_log])
14
+ if is_true?(configs[:cache_log])
15
+ require 'restash_rails/log_subscriber/subscribers/cache'
16
+ RestashRails::LogSubscriber::Cache.attach_to :active_support
17
+ end
18
+ end
19
+
20
+ def is_true?(variable)
21
+ (variable.present? && (variable == true || variable == 'true'))
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,23 @@
1
+ require 'action_mailer/log_subscriber'
2
+
3
+ module RestashRails
4
+ module LogSubscriber
5
+ class ActionMailer < ::ActionMailer::LogSubscriber
6
+ def deliver(event)
7
+ ::RestashRails.logger.info(generate_message(event, 'deliver'))
8
+ end
9
+
10
+ private
11
+
12
+ def generate_message(event, action)
13
+ {
14
+ to: event.payload[:to],
15
+ duration: event.duration.round(2),
16
+ action: action,
17
+ log_tag: :action_mailer
18
+ }
19
+
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,25 @@
1
+ require 'action_view/log_subscriber'
2
+
3
+ module RestashRails
4
+ module LogSubscriber
5
+ class ActionView < ::ActionView::LogSubscriber
6
+ def render_template(event)
7
+ ::RestashRails.logger.info(generate_message(event))
8
+ end
9
+ alias :render_partial :render_template
10
+ alias :render_collection :render_template
11
+
12
+ private
13
+
14
+ def generate_message(event)
15
+ message = {
16
+ duration: event.duration.round(2),
17
+ identifier: from_rails_root(event.payload[:identifier]),
18
+ log_tag: :action_view
19
+ }
20
+ message.merge!(layout: from_rails_root(event.payload[:layout])) unless event.payload[:layout].nil?
21
+ return message
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,22 @@
1
+ require 'active_record/log_subscriber'
2
+
3
+ module RestashRails
4
+ module LogSubscriber
5
+ class ActiveRecord < ::ActiveRecord::LogSubscriber
6
+ def sql(event)
7
+ ::RestashRails.logger.debug(generate_message(event))
8
+ end
9
+
10
+ private
11
+
12
+ def generate_message(event)
13
+ {
14
+ sql: event.payload[:sql].to_s,
15
+ duration: event.duration.round(2),
16
+ name: event.payload[:name],
17
+ log_tag: :active_record
18
+ }
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,74 @@
1
+ require 'active_support/log_subscriber'
2
+ require 'restash_rails/rails_ext/action_pack/action_controller/metal/instrumentation'
3
+
4
+ module RestashRails
5
+ module LogSubscriber
6
+ class ActiveSupport < ::ActionController::LogSubscriber
7
+ def process_action(event)
8
+ log_message = generate_message(event)
9
+ if log_message[:response_code] >= 500
10
+ logger.error(log_message)
11
+ elsif log_message[:response_code] >= 300
12
+ logger.warn(log_message)
13
+ else
14
+ logger.info(log_message)
15
+ end
16
+ end
17
+
18
+ def redirect_to(event)
19
+ log_message = generate_message(event)
20
+ logger.info (log_message)
21
+ end
22
+
23
+ def logger
24
+ ::RestashRails.logger
25
+ end
26
+
27
+ private
28
+
29
+ def exception_formatter(payload)
30
+ return {} if payload[:exception].nil?
31
+ exception = payload[:exception]
32
+ { class: exception.class, message: exception.message, backtrace: exception.backtrace }
33
+ end
34
+
35
+
36
+ def extract_status(payload)
37
+ if (status = payload[:status])
38
+ status.to_i
39
+ elsif (error = payload[:exception])
40
+ exception, message = error
41
+ get_error_status_code(exception)
42
+ else
43
+ 200
44
+ end
45
+ end
46
+
47
+ def get_error_status_code(exception)
48
+ status = ::ActionDispatch::ExceptionWrapper.rescue_responses[exception]
49
+ ::Rack::Utils.status_code(status)
50
+ end
51
+
52
+ def generate_message(event)
53
+ payload = event.payload
54
+ excepted_params = %w(controller action format id)
55
+ {
56
+ controller: payload[:controller].to_s,
57
+ action: payload[:action].to_s,
58
+ request_method: payload[:method].to_s,
59
+ uuid: payload[:request_id],
60
+ response_code: extract_status(payload),
61
+ path: payload[:path].to_s,
62
+ format: payload[:format].to_s,
63
+ request_params: (payload[:params].except(*excepted_params) rescue {}),
64
+ duration: event.duration.to_f.round(2),
65
+ redirect_to: payload[:location] || '',
66
+ db_duration: ((payload[:db_runtime] * 100).round(2)/100.0 rescue 0.0),
67
+ view_duration: ((payload[:view_runtime] * 100).round(2)/100.0 rescue 0.0),
68
+ log_tag: :action_controller,
69
+ exception: exception_formatter(payload)
70
+ }
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,69 @@
1
+ require 'restash_rails/rails_ext/active_support/cache/store'
2
+ require 'active_support/log_subscriber'
3
+
4
+ module RestashRails
5
+ module LogSubscriber
6
+ class Cache < ::ActiveSupport::LogSubscriber
7
+ def cache_read(event)
8
+ log(event)
9
+ end
10
+ def cache_delete_tag_tree(event)
11
+ log(event)
12
+ end
13
+ def cache_delete_wiled_card(event)
14
+ log(event)
15
+ end
16
+ def cache_write_value(event)
17
+ log(event)
18
+ end
19
+ def cache_write_tags(event)
20
+ log(event)
21
+ end
22
+ def cache_write(event)
23
+ log(event)
24
+ end
25
+ def cache_fetch(event)
26
+ log(event)
27
+ end
28
+ def cache_delete_tag_keys(event)
29
+ log(event)
30
+ end
31
+ def cache_delete(event)
32
+ log(event)
33
+ end
34
+
35
+ def logger
36
+ ::RestashRails.logger
37
+ end
38
+
39
+ private
40
+
41
+ def log(event)
42
+ message = generate_message(event)
43
+ (duration > 100) ?
44
+ logger.debug(message.merge({ execution: 'slow' })) :
45
+ logger.debug(message)
46
+ end
47
+
48
+ def generate_message(event)
49
+ payload = event.payload
50
+ message = {
51
+ name: event.name,
52
+ duration: event.duration,
53
+ cache_key: payload[:key],
54
+ host: payload[:host],
55
+ port: payload[:port],
56
+ expire_in: payload[:expire_in],
57
+ log_tag: :cache
58
+ }
59
+ message.merge(exception_formatter(payload))
60
+ end
61
+
62
+ def exception_formatter(payload)
63
+ return {} if payload[:exception].nil?
64
+ exception_class, message = payload[:exception]
65
+ { exception_class: exception_class, message: message}
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,93 @@
1
+ require 'tcp_timeout'
2
+
3
+ module RestashRails
4
+ class Logger
5
+ include ::Logger::Severity
6
+ attr_accessor :app_name, :level, :outputter, :formatter, :logstash_host, :logstash_port, :timeout_options
7
+ DEFAULT_TIMEOUT = 0.010
8
+
9
+ def initialize(configs)
10
+ self.level = configs[:level] || 'DEBUG'
11
+ @logstash_host = configs[:host] || '127.0.0.1' #logstash host
12
+ @logstash_port = configs[:port].to_i || 5960 #logstash port
13
+ @app_name = configs[:app_name] || ENV['APP_NAME'] || Rails.application.class.name
14
+ #TCP connection timeouts in milliseconds
15
+ if configs[:timeout_options].present?
16
+ configs[:timeout_options].each{ |k,v| configs[:timeout_options][k] = v.to_f }
17
+ @timeout_options = configs[:timeout_options]
18
+ else
19
+ @timeout_options = { connect_timeout: DEFAULT_TIMEOUT, write_timeout: DEFAULT_TIMEOUT, read_timeout: DEFAULT_TIMEOUT }
20
+ end
21
+ set_formatter(configs)
22
+ end
23
+
24
+ ::Logger::Severity.constants.each do |severity|
25
+ class_eval <<-METHOD, __FILE__, __LINE__ + 1
26
+
27
+ def #{severity.downcase}? # def debug?
28
+ log_severity_allowed?(#{severity}) # log_severity_allowed?(DEBUG)
29
+ end # end
30
+
31
+ def #{severity.downcase}(message = nil) # def debug(message = nil)
32
+ log('#{severity.upcase}', message) # log('DEBUG', message)
33
+ end # end
34
+ METHOD
35
+ end
36
+
37
+ def level=(level)
38
+ return @level if @level.present?
39
+ if level.is_a?(Integer)
40
+ ::Logger::Severity.constants.each { |severity|
41
+ return @level = severity if level == severity
42
+ }
43
+ raise "Log level #{level} not recognised"
44
+ else
45
+ desired_level = level.to_s.upcase
46
+ raise "Log level #{level} not recognised" unless self.class.constants.include?(desired_level.to_sym)
47
+ return @level = class_eval(desired_level)
48
+ end
49
+ end
50
+
51
+ private
52
+
53
+ def set_formatter(configs)
54
+ formatter_name = configs[:formatter] || Formatter::Default
55
+ @formatter = formatter_name.new
56
+ end
57
+
58
+ def log(severity, message = nil)
59
+ severity_value = class_eval(severity.to_s.upcase)
60
+ return unless log_severity_allowed?(severity_value)
61
+ log_message = {}
62
+ log_message[:severity] = severity
63
+ log_message[:app_name] = app_name
64
+ log_message[:rails_env] = environment
65
+ log_message.merge!(formatter.format_message(message))
66
+ log_message = log_message.with_indifferent_access
67
+ log_message[:log_tag] ||= :custom
68
+ write(log_message)
69
+ end
70
+
71
+ def log_severity_allowed?(severity)
72
+ return false unless severity.is_a?(Integer)
73
+ severity >= level
74
+ end
75
+
76
+ def write(data)
77
+ json_data = data.to_json
78
+ sock = ::TCPTimeout::TCPSocket.new(logstash_host, logstash_port, timeout_options)
79
+ sock.write(json_data)
80
+ sock.close
81
+ rescue => e
82
+ failures_logger = ::Logger.new(STDOUT)
83
+ failures_logger.error({ status: "Failed to write data to #{logstash_host}:#{logstash_port}", exception: e, data: data })
84
+ end
85
+
86
+ def environment
87
+ (defined?(ENV['RAILS_ENV']) && ENV['RAILS_ENV']) ||
88
+ (defined?(Rails.env) && Rails.env) ||
89
+ (defined?(ENV['RACK_ENV']) && ENV['RACK_ENV']) ||
90
+ :unknown
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,47 @@
1
+ require 'action_view/log_subscriber'
2
+ require 'action_controller/log_subscriber'
3
+ require 'active_support/core_ext/module/attribute_accessors'
4
+ require 'active_support/core_ext/string/inflections'
5
+ require 'active_support/ordered_options'
6
+ require 'restash_rails/rails_ext/rack/logger'
7
+
8
+ module RestashRails
9
+ module LogsUnsubscriber
10
+ def disable_additional_logs
11
+ disable_rack_cache_verbose_output(Rails.application) if defined?(Rails)
12
+ ::ActiveSupport::LogSubscriber.log_subscribers.each do |subscriber|
13
+ case subscriber.class.name
14
+ when 'ActionView::LogSubscriber'
15
+ unsubscribe(:action_view, subscriber)
16
+ when 'ActionController::LogSubscriber'
17
+ unsubscribe(:action_controller, subscriber)
18
+ when 'ActionMailer::LogSubscriber'
19
+ unsubscribe(:action_mailer, subscriber)
20
+ when 'ActiveRecord::LogSubscriber'
21
+ unsubscribe(:active_record, subscriber)
22
+ end
23
+ end
24
+ end
25
+
26
+ private
27
+
28
+ def unsubscribe(component, subscriber)
29
+ events = subscriber.public_methods(false).reject { |method| method.to_s == 'call' }
30
+ events.each do |event|
31
+ ::ActiveSupport::Notifications.notifier.listeners_for("#{event}.#{component}").each do |listener|
32
+ if listener.instance_variable_get('@delegate') == subscriber
33
+ ::ActiveSupport::Notifications.unsubscribe listener
34
+ end
35
+ end
36
+ end
37
+ end
38
+
39
+ def rack_cache_hashlike?(app)
40
+ app.config.action_dispatch.rack_cache && app.config.action_dispatch.rack_cache.respond_to?(:[]=)
41
+ end
42
+
43
+ def disable_rack_cache_verbose_output(app)
44
+ app.config.action_dispatch.rack_cache[:verbose] = false if rack_cache_hashlike?(app)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,24 @@
1
+ require 'action_dispatch/middleware/debug_exceptions'
2
+
3
+ module ActionDispatch
4
+ class DebugExceptions
5
+ alias_method :default_log_error, :log_error
6
+ def log_error(env, wrapper)
7
+ exception = wrapper.exception
8
+ if exception.is_a?(ActionController::RoutingError)
9
+ message = {
10
+ request_method: env['REQUEST_METHOD'],
11
+ request_path: env['REQUEST_PATH'],
12
+ response_code: wrapper.status_code,
13
+ log_tag: :action_controller,
14
+ exception: { class: exception.class.name, message: exception.message }
15
+ }
16
+ ::RestashRails.logger.warn(message)
17
+ else
18
+ default_log_error env, wrapper
19
+ end
20
+ rescue
21
+ default_log_error env, wrapper
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,26 @@
1
+ module ActionController
2
+ module Instrumentation
3
+ def process_action(*args)
4
+ raw_payload = {
5
+ controller: self.class.name,
6
+ action: self.action_name,
7
+ params: request.filtered_parameters,
8
+ format: request.format.try(:ref),
9
+ method: request.method,
10
+ path: (request.fullpath rescue 'unknown'),
11
+ request_id: (env['action_dispatch.request_id'] rescue 'not_defined')
12
+ }
13
+ ActiveSupport::Notifications.instrument('start_processing.action_controller', raw_payload.dup)
14
+
15
+ ActiveSupport::Notifications.instrument('process_action.action_controller', raw_payload) do |payload|
16
+ begin
17
+ result = super
18
+ payload[:status] = response.status
19
+ result
20
+ ensure
21
+ append_info_to_payload(payload)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,11 @@
1
+ module ActiveSupport
2
+ module Cache
3
+ class Store
4
+ alias default_instrument instrument
5
+ def instrument(operation, key, options = nil)
6
+ self.class.instrument = true
7
+ default_instrument(operation, key, options, &Proc.new)
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,9 @@
1
+ class Hash
2
+ def deep_symbolize_keys
3
+ inject({}) { |result, (key, value)|
4
+ value = value.deep_symbolize_keys if value.is_a?(Hash)
5
+ result[(key.to_sym rescue key) || key] = value
6
+ result
7
+ }
8
+ end unless Hash.method_defined?(:deep_symbolize_keys)
9
+ end
@@ -0,0 +1,25 @@
1
+ require 'active_support/concern'
2
+ require 'rails/rack/logger'
3
+
4
+ module Rails
5
+ module Rack
6
+ # Overwrites defaults of Rails::Rack::Logger that cause
7
+ # unnecessary logging.
8
+ # This effectively removes the log lines from the log
9
+ # that say:
10
+ # Started GET / for 192.168.2.1...
11
+ class Logger
12
+ # Overwrites Rails 3.2 code that logs new requests
13
+ def call_app(*args)
14
+ env = args.last
15
+ @app.call(env)
16
+ ensure
17
+ ActiveSupport::LogSubscriber.flush_all!
18
+ end
19
+
20
+ # Overwrites Rails 3.0/3.1 code that logs new requests
21
+ def before_dispatch(_env)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,12 @@
1
+ require 'rails/railtie'
2
+
3
+ module RestashRails
4
+ class Railtie < ::Rails::Railtie
5
+ config.restash_rails = ::ActiveSupport::OrderedOptions.new
6
+ config.restash_rails.enabled = false
7
+ initializer :restash, before: :initialize_logger do |app|
8
+ app.config.restash_rails = app.config.restash_rails.deep_symbolize_keys
9
+ app.config.logger = RestashRails.setup(app.config.restash_rails)
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,24 @@
1
+ module Resque
2
+ module Failure
3
+ class RestashLogger < Resque::Failure::Base
4
+ def save
5
+ begin
6
+ message = {
7
+ exception: {
8
+ class: exception.class,
9
+ message: exception.message,
10
+ backtrace: exception.backtrace
11
+ },
12
+ worker: worker.to_s,
13
+ queue: queue,
14
+ extra_data: payload,
15
+ log_tag: :resque_failure
16
+ }
17
+ ::Rails.logger.error(message)
18
+ rescue => e
19
+ puts "Failed to send rescue_failure log: #{e.message}\n#{e.backtrace}"
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,7 @@
1
+ module Resque
2
+ module Logging
3
+ def self.log(severity, message)
4
+ RestashRails.logger.send(severity, { resque_message: message, log_tag: :resque })
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,38 @@
1
+ module Resque
2
+ module Plugins
3
+ module RestashLogger
4
+ # Executed on the Resque worker
5
+ def before_perform_logstash_logger(*args)
6
+ @resque_job_uuid = SecureRandom.uuid
7
+ log 'Executing', args
8
+ end
9
+
10
+ def after_perform_logstash_logger(*args)
11
+ log 'Finished', args
12
+ end
13
+
14
+ def on_failure_logstash_logger(*args)
15
+ log 'Failed', args, :error
16
+ end
17
+
18
+ # Executed on the enqueueing instance
19
+ def after_enqueue_logstash_logger(*args)
20
+ log 'Enqueued', args
21
+ end
22
+
23
+ def after_schedule_send_monitor_data(*args)
24
+ log 'Scheduled', args
25
+ end
26
+
27
+ def log(status, args, severity = :info)
28
+ log_arguments = { status: status, extra_data: args, class: self.name, log_tag: :resque_hooks }
29
+ if args.is_a?(Array) && args[0].is_a?(Exception)
30
+ exception = args.shift
31
+ log_arguments[:exception] = { class: exception.class, message: exception.message, backtrace: exception.backtrace }
32
+ end
33
+ log_arguments[:resque_job_uuid] = @resque_job_uuid if @resque_job_uuid.present?
34
+ Rails.logger.send(severity, log_arguments)
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,3 @@
1
+ module RestashRails
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,53 @@
1
+ require 'restash_rails/rails_ext/action_dispatch/middleware/debug_exceptions'
2
+ require 'rack/utils'
3
+ require 'restash_rails/version'
4
+ require 'restash_rails/logger'
5
+ require 'restash_rails/logs_unsubscriber'
6
+ require 'restash_rails/log_subscriber/log_subscriber'
7
+ require 'restash_rails/formatters/default'
8
+ require 'restash_rails/railtie' if defined?(Rails::Railtie)
9
+ require 'restash_rails/rails_ext/rack/logger'
10
+ require 'restash_rails/rails_ext/core_ext/hash'
11
+
12
+ module RestashRails
13
+ mattr_accessor :logger
14
+ extend RestashRails::LogSubscriber
15
+ extend RestashRails::LogsUnsubscriber
16
+
17
+ class << self
18
+ def setup(configs = {})
19
+ return unless configs.present? && configs.is_a?(Hash)
20
+ configs = configs.with_indifferent_access
21
+ return unless is_true?(configs[:enabled])
22
+ subscribe_logs(configs)
23
+ disable_additional_logs unless configs[:additional_log] == true
24
+ add_exception_statuses(configs[:exception_statuses] || [])
25
+ @@logger = RestashRails::Logger.new(configs)
26
+ @@logger
27
+ end
28
+
29
+ private
30
+
31
+ # exception_statuses has to be an array of hashes.
32
+ # Each hash has to contain status and types.
33
+ # Types is an array of Exception classes
34
+ # Example:
35
+ # error_401 = {:status => 401, :types => [Exceptions::AccessDenied, Exceptions::MyException]}
36
+ # error_422 = {:status => 422, :types => [Exceptions::InvalidParams]}
37
+ # exception_statuses = [error_401, error_422]
38
+
39
+ def add_exception_statuses(exception_statuses = [])
40
+ return unless exception_statuses.is_a?(Array) || exception_statuses.size > 0
41
+ exception_statuses.each do |error|
42
+ next unless error.is_a?(Hash)
43
+ error = error.with_indifferent_access
44
+ next unless error[:status].present? || (error[:types].present? && error[:types].is_a?(Array))
45
+ status_symbol = ::Rack::Utils::HTTP_STATUS_CODES[error[:status].to_i].parameterize.underscore.to_sym
46
+ existing_exceptions = ::ActionDispatch::ExceptionWrapper.rescue_responses.keys
47
+ (error[:types].map(&:to_s) - existing_exceptions).each do |exceptions_class|
48
+ ::ActionDispatch::ExceptionWrapper.rescue_responses.merge!({ exceptions_class => status_symbol })
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'restash_rails/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'restash_rails'
8
+ spec.version = RestashRails::VERSION
9
+ spec.authors = ['dmitri86git']
10
+ spec.email = ['dmitri@yotpo.com']
11
+
12
+ spec.summary = 'This gem sends your Rails application logs to logstash.'
13
+ spec.description = 'Add configurations to application.config.restash_rails and have fun.'
14
+ spec.homepage = 'https://github.com/YotpoLtd/restash-rails'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject{ |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = 'exe'
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_development_dependency 'bundler', '~> 1.10'
23
+ spec.add_development_dependency 'rake', '~> 10.0'
24
+ spec.add_development_dependency 'rspec', '~> 3.0'
25
+ spec.add_dependency 'rails'
26
+ spec.add_dependency 'tcp_timeout'
27
+ end
metadata ADDED
@@ -0,0 +1,145 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: restash_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - dmitri86git
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-05-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: tcp_timeout
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: Add configurations to application.config.restash_rails and have fun.
84
+ email:
85
+ - dmitri@yotpo.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - bin/console
99
+ - bin/setup
100
+ - lib/restash_rails.rb
101
+ - lib/restash_rails/formatters/default.rb
102
+ - lib/restash_rails/log_subscriber/log_subscriber.rb
103
+ - lib/restash_rails/log_subscriber/subscribers/action_mailer.rb
104
+ - lib/restash_rails/log_subscriber/subscribers/action_view.rb
105
+ - lib/restash_rails/log_subscriber/subscribers/active_record.rb
106
+ - lib/restash_rails/log_subscriber/subscribers/active_support.rb
107
+ - lib/restash_rails/log_subscriber/subscribers/cache.rb
108
+ - lib/restash_rails/logger.rb
109
+ - lib/restash_rails/logs_unsubscriber.rb
110
+ - lib/restash_rails/rails_ext/action_dispatch/middleware/debug_exceptions.rb
111
+ - lib/restash_rails/rails_ext/action_pack/action_controller/metal/instrumentation.rb
112
+ - lib/restash_rails/rails_ext/active_support/cache/store.rb
113
+ - lib/restash_rails/rails_ext/core_ext/hash.rb
114
+ - lib/restash_rails/rails_ext/rack/logger.rb
115
+ - lib/restash_rails/railtie.rb
116
+ - lib/restash_rails/resque/failure/restash_logger.rb
117
+ - lib/restash_rails/resque/logging.rb
118
+ - lib/restash_rails/resque/plugins/restash_logger.rb
119
+ - lib/restash_rails/version.rb
120
+ - restash_rails.gemspec
121
+ homepage: https://github.com/YotpoLtd/restash-rails
122
+ licenses:
123
+ - MIT
124
+ metadata: {}
125
+ post_install_message:
126
+ rdoc_options: []
127
+ require_paths:
128
+ - lib
129
+ required_ruby_version: !ruby/object:Gem::Requirement
130
+ requirements:
131
+ - - ">="
132
+ - !ruby/object:Gem::Version
133
+ version: '0'
134
+ required_rubygems_version: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ requirements: []
140
+ rubyforge_project:
141
+ rubygems_version: 2.6.12
142
+ signing_key:
143
+ specification_version: 4
144
+ summary: This gem sends your Rails application logs to logstash.
145
+ test_files: []