dreamcatcher 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in dreamcatcher.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Willem van Bergen
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # Dreamcatcher
2
+
3
+ A simple gem to catch exceptions and send email notifications.
4
+
5
+ This gem is especially made for monitoring tasks, like rake tasks or background jobs.
6
+ It can also capture messages you send to a logger during the monitored code, and
7
+ include the log snippet in the notification.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ gem 'dreamcatcher'
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install dreamcatcher
22
+
23
+ ## Usage
24
+
25
+ Use `Dreamcatcher.monitor` to monitor a block of code for exceptions
26
+
27
+ logger = Logger.new($stdout)
28
+ Dreamcatcher.monitor(logger: logger) do
29
+ logger.debug "progress"
30
+ raise 'omg ponies'
31
+ end
32
+
33
+ If Dreamcatcher catches an exception, it will send an email, and re-raise the exception.
34
+
35
+ You can configure Dreamcatcher using the `configuration` object.
36
+ You can provide a static value or a block that will be dynamically evaluated
37
+ when the value is needed.
38
+
39
+ Dreamcatcher.configuration.from = 'willem@example.com'
40
+ Dreamcatcher.configuration.to = 'willem+exceptions@example.com'
41
+ Dreamcatcher.configuration.subject = lambda do |context|
42
+ "[My app] #{context.exception.class.name}: #{context.exception.message}"
43
+ end
44
+
45
+ # This defines whether the email will actually be delivered.
46
+ Dreamcatcher.configuration.subject.deliver = lambda { RACK_ENV == 'production' }
47
+
48
+ # Dreamcatcher uses the pony gem to send emails: https://github.com/benprew/pony
49
+ # The following options are copied directly to `Pony.mail`
50
+
51
+ Dreamcatcher.configuration.via = :smtp
52
+ Dreamcatcher.configuration.via_options = { ... }
53
+
54
+ # You can specify what templates to use for the emails.
55
+ # Dreamcatcher ships with basic templates, so you can leave these options blank.
56
+ # It will look for `#{template_dir}/#{template}.html.erb` for the HTML part
57
+ # and `#{template_dir}/#{template}.text.erb` for the plain text part of the email.
58
+
59
+ Dreamcatcher.configuration.template_dir = "./email_templates"
60
+ Dreamcatcher.configuration.template = lambda do |context|
61
+ # Use a custom template for a particular exception
62
+ if context.exception.class == MyAwesomeException
63
+ 'my_awesome_exception'
64
+ else
65
+ 'generic_exception'
66
+ end
67
+ end
68
+
69
+
70
+
71
+ ## Contributing
72
+
73
+ 1. Fork it
74
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
75
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
76
+ 4. Push to the branch (`git push origin my-new-feature -u`)
77
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new do |t|
5
+ t.libs << "test"
6
+ t.test_files = FileList['test/*_test.rb']
7
+ t.verbose = true
8
+ end
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'dreamcatcher/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "dreamcatcher"
8
+ gem.version = Dreamcatcher::VERSION
9
+ gem.authors = ["Willem van Bergen"]
10
+ gem.email = ["willem@railsdoctors.com"]
11
+ gem.description = %q{Catch exceptions and send email notifications with context.}
12
+ gem.summary = %q{Catch exceptions and send email notifications with context.}
13
+ gem.homepage = "https://github.com/wvanbergen/dreamcatcher"
14
+
15
+ gem.files = `git ls-files`.split($/)
16
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.require_paths = ["lib"]
19
+
20
+ gem.add_runtime_dependency("pony")
21
+ end
@@ -0,0 +1,20 @@
1
+ module Dreamcatcher
2
+ extend self
3
+
4
+ def monitor(options = {}, &block)
5
+ Dreamcatcher::Monitor.new(configuration).monitor(options, &block)
6
+ end
7
+
8
+ def configuration
9
+ @configuration ||= Dreamcatcher::Configuration.new
10
+ end
11
+
12
+ TEMPLATE_DIR = File.expand_path('../dreamcatcher/templates', __FILE__)
13
+ end
14
+
15
+ require "dreamcatcher/version"
16
+ require "dreamcatcher/configuration"
17
+ require "dreamcatcher/monitor"
18
+ require "dreamcatcher/exception_context"
19
+ require "dreamcatcher/logger_proxy"
20
+ require "dreamcatcher/mailer"
@@ -0,0 +1,27 @@
1
+ class Dreamcatcher::Configuration
2
+
3
+ attr_accessor :exception_class,
4
+ :to, :from, :subject,
5
+ :deliver, :via, :via_options,
6
+ :template, :template_dir
7
+
8
+ def initialize
9
+ @exception_class = StandardError
10
+ @from = 'exceptions@example.com'
11
+ @subject = lambda do |context|
12
+ "Exception #{context.exception.class.name}: #{context.exception.message}"
13
+ end
14
+
15
+ @template_dir = Dreamcatcher::TEMPLATE_DIR
16
+ @template = 'generic_exception'
17
+
18
+ @via = :sendmail
19
+ @via_options = nil
20
+ @deliver = false
21
+ end
22
+
23
+ def evaluate(symbol, *args)
24
+ value = self.send(symbol)
25
+ value.respond_to?(:call) ? value.call(*args) : value
26
+ end
27
+ end
@@ -0,0 +1,9 @@
1
+ class Dreamcatcher::ExceptionContext
2
+
3
+ attr_reader :exception, :log_entries, :other, :timestamp
4
+
5
+ def initialize(exception, log_entries, other = {})
6
+ @exception, @log_entries, @other = exception, log_entries, other
7
+ @timestamp = Time.now
8
+ end
9
+ end
@@ -0,0 +1,79 @@
1
+ require 'logger'
2
+
3
+ class Dreamcatcher::LoggerProxy
4
+
5
+ attr_reader :original_logger, :log_entries
6
+
7
+ def initialize(logger)
8
+ @original_logger = logger
9
+ @log_entries = []
10
+ end
11
+
12
+ def capture(&block)
13
+ register_logger_monkeypatch unless @original_logger.nil?
14
+ yield if block_given?
15
+ return self
16
+ ensure
17
+ deregister_logger_monkeypatch unless @original_logger.nil?
18
+ end
19
+
20
+ def self.capture(logger, &block)
21
+ Dreamcatcher::LoggerProxy.new(logger).capture(&block)
22
+ end
23
+
24
+ protected
25
+
26
+ def register_logger_monkeypatch
27
+ @original_logger.instance_variable_set(:"@_captured_entries", @log_entries)
28
+ class << @original_logger
29
+ def add_with_capture(severity, prog, message = nil, &block)
30
+ message = yield if message.nil? && block_given?
31
+ @_captured_entries << LogEntry.new(severity, prog, message)
32
+ add_without_capture(severity, prog, message)
33
+ end
34
+ alias_method :add_without_capture, :add
35
+ alias_method :add, :add_with_capture
36
+ end
37
+ end
38
+
39
+ def deregister_logger_monkeypatch
40
+ class << @original_logger
41
+ alias_method :add, :add_without_capture
42
+ undef_method :add_without_capture
43
+ undef_method :add_with_capture
44
+ end
45
+ @original_logger.send :remove_instance_variable, :"@_captured_entries"
46
+ end
47
+
48
+ class LogEntry
49
+ attr_reader :severity, :message, :timestamp
50
+
51
+ def initialize(severity, prog, message, timestamp = nil)
52
+ @severity = severity
53
+ @prog = prog
54
+ @message = message
55
+ @timestamp = timestamp || Time.now
56
+ end
57
+
58
+ def to_s(format = '%t [%s] %m')
59
+ format.
60
+ sub('%s', format_severity).
61
+ sub('%m', @message || '').
62
+ sub('%p', @prog || '').
63
+ sub('%t', format_timestamp)
64
+ end
65
+
66
+ protected
67
+
68
+ # Severity label for logging (max 5 chars).
69
+ SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
70
+
71
+ def format_severity
72
+ SEV_LABEL[severity] || 'ANY'
73
+ end
74
+
75
+ def format_timestamp
76
+ timestamp.strftime('%F %T %Z')
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,101 @@
1
+ require "delegate"
2
+ require "pony"
3
+ require "erb"
4
+
5
+ class Dreamcatcher::Mailer
6
+
7
+ attr_reader :configuration
8
+
9
+ def initialize(configuration)
10
+ @configuration = configuration
11
+ end
12
+
13
+ def handle_exception(context)
14
+ email_options = build_email_options(context)
15
+ if configuration.evaluate(:deliver, context)
16
+ Pony.mail(email_options)
17
+ else
18
+ # TODO: print / log email somewhere
19
+ end
20
+ end
21
+
22
+ def build_email_options(context)
23
+
24
+ options = {
25
+ :to => configuration.evaluate(:to, context),
26
+ :from => configuration.evaluate(:from, context),
27
+ :subject => configuration.evaluate(:subject, context),
28
+ :via => configuration.evaluate(:via, context),
29
+ :via_options => configuration.evaluate(:via_options, context)
30
+ }
31
+
32
+ options[:body] = render_body(:text, context, options)
33
+ options[:html_body] = render_body(:html, context, options)
34
+
35
+ options.delete_if { |k, v| v.nil? }
36
+ raise "E-mail has no to recipient!" unless options[:to]
37
+ raise "E-mail has no body!" unless options[:body] || options[:html_body]
38
+
39
+ options
40
+ end
41
+
42
+ def render_body(type, context, options)
43
+ template_dir = configuration.evaluate(:template_dir, context)
44
+ template = configuration.evaluate(:template, context)
45
+ template_file = erb_template_file(template_dir, template, type)
46
+ email_context = EmailContext.new(context, options)
47
+
48
+ if File.exists?(template_file)
49
+ layout_file = erb_template_file(template_dir, 'layout', type)
50
+ if File.exists?(layout_file)
51
+ render_erb_template(layout_file, email_context) do
52
+ render_erb_template(template_file, email_context)
53
+ end
54
+ else
55
+ render_erb_template(template_file, email_context)
56
+ end
57
+ else
58
+ nil
59
+ end
60
+ end
61
+
62
+ def render_erb_template(template_file, context, &block)
63
+ ERB.new(File.read(template_file), nil, '<>').result(context.get_binding(&block))
64
+ end
65
+
66
+ def erb_template_file(dir, name, type)
67
+ File.join(dir, "#{name}.#{type}.erb")
68
+ end
69
+
70
+
71
+ class EmailContext < SimpleDelegator
72
+ def initialize(context, options)
73
+ super(context)
74
+ @context, @options = context, options
75
+ end
76
+
77
+ def subject
78
+ @options[:subject]
79
+ end
80
+
81
+ def to
82
+ @options[:to]
83
+ end
84
+
85
+ def cc
86
+ @options[:cc]
87
+ end
88
+
89
+ def bcc
90
+ @options[:bcc]
91
+ end
92
+
93
+ def from
94
+ @options[:from]
95
+ end
96
+
97
+ def get_binding
98
+ binding
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,27 @@
1
+ class Dreamcatcher::Monitor
2
+
3
+ attr_reader :configuration, :handlers
4
+
5
+ def initialize(configuration)
6
+ @configuration = configuration
7
+ @handlers = build_handlers
8
+ end
9
+
10
+ def monitor(options = {}, &block)
11
+ @context = options[:context] || {}
12
+ logger_proxy = Dreamcatcher::LoggerProxy.new(options[:logger])
13
+ logger_proxy.capture { block.call }
14
+
15
+ rescue @configuration.exception_class => exception
16
+ context = Dreamcatcher::ExceptionContext.new(exception, logger_proxy.log_entries)
17
+ handlers.each { |handler| handler.handle_exception(context) }
18
+ raise
19
+ end
20
+
21
+ protected
22
+
23
+ def build_handlers
24
+ mailer = Dreamcatcher::Mailer.new(configuration)
25
+ [mailer]
26
+ end
27
+ end
@@ -0,0 +1 @@
1
+ require 'rake'
@@ -0,0 +1,38 @@
1
+ <h3> Exception: <%=exception.class.name %> </h3>
2
+ <table>
3
+ <tr>
4
+ <th style="text-align: left;"> Exception </th>
5
+ <td> <code><%=exception.class.name %></code> </td>
6
+ </tr>
7
+
8
+ <tr>
9
+ <th style="text-align: left;"> Timestamp </th>
10
+ <td> <%= timestamp %> </td>
11
+ </tr>
12
+
13
+ <% if !exception.message.nil? && exception.message != '' %>
14
+ <tr>
15
+ <th style="text-align: left;"> Message </th>
16
+ <td> <%= exception.message %> </td>
17
+ </tr>
18
+ <% end %>
19
+ </table>
20
+
21
+ <% if exception.backtrace %>
22
+ <h3> Backtrace </h3>
23
+ <pre style="font-family:monospace;">
24
+ <% exception.backtrace.each do |line| %>
25
+ <%= line %>
26
+ <% end %>
27
+ </pre>
28
+ <% end %>
29
+
30
+
31
+ <% if log_entries.any? %>
32
+ <h3> Log </h3>
33
+ <pre style="font-family:monospace;">
34
+ <% log_entries.each do |entry| %>
35
+ <%= entry.to_s %>
36
+ <% end %>
37
+ </pre>
38
+ <% end %>
@@ -0,0 +1,25 @@
1
+ # Exception: <%=exception.class.name %>
2
+
3
+ Exception: <%=exception.class.name %>
4
+ Timestamp: <%= timestamp %>
5
+ <% if !exception.message.nil? && exception.message != '' %>
6
+ Message: <%= exception.message %>
7
+ <% end %>
8
+
9
+
10
+ <% if exception.backtrace %>
11
+ ## Backtrace
12
+
13
+ <% exception.backtrace.each do |line| %>
14
+ <%= line %>
15
+ <% end %>
16
+ <% end %>
17
+
18
+
19
+ <% if log_entries.any? %>
20
+ ## Log
21
+
22
+ <% log_entries.each do |entry| %>
23
+ <%= entry.to_s %>
24
+ <% end %>
25
+ <% end %>
@@ -0,0 +1,5 @@
1
+ <html>
2
+ <body>
3
+ <%= yield %>
4
+ </body>
5
+ </html>
@@ -0,0 +1,3 @@
1
+ module Dreamcatcher
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,16 @@
1
+ require 'test_helper'
2
+ require 'logger'
3
+
4
+ Dreamcatcher.configuration.to = 'example@example.com'
5
+ Dreamcatcher.configuration.deliver = false
6
+
7
+ class DreamcatcherTest < Test::Unit::TestCase
8
+
9
+ def test_monitor_should_reraise_exception
10
+ assert_raises(RuntimeError) do
11
+ Dreamcatcher.monitor do
12
+ raise "error"
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,24 @@
1
+ require 'test_helper'
2
+ require 'logger'
3
+
4
+ class LoggerProxyTest < Test::Unit::TestCase
5
+
6
+ def test_logger_capture
7
+ logger = Logger.new("/dev/null")
8
+ proxy = Dreamcatcher::LoggerProxy.capture(logger) do
9
+ logger.info "hello world"
10
+ end
11
+ logger.info "goodbye world"
12
+
13
+ assert_equal proxy.log_entries.size, 1
14
+ assert_equal proxy.log_entries.first.message, "hello world"
15
+ end
16
+
17
+ def test_capture_without_logger
18
+ logger = Logger.new("/dev/null")
19
+ proxy = Dreamcatcher::LoggerProxy.capture(nil) do
20
+ logger.info "hello world"
21
+ end
22
+ assert_equal proxy.log_entries.size, 0
23
+ end
24
+ end
@@ -0,0 +1,5 @@
1
+ lib = File.expand_path('../../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+
4
+ require 'test/unit'
5
+ require 'dreamcatcher'
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dreamcatcher
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Willem van Bergen
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-02-10 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: pony
16
+ requirement: &70145515587540 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *70145515587540
25
+ description: Catch exceptions and send email notifications with context.
26
+ email:
27
+ - willem@railsdoctors.com
28
+ executables: []
29
+ extensions: []
30
+ extra_rdoc_files: []
31
+ files:
32
+ - .gitignore
33
+ - Gemfile
34
+ - LICENSE.txt
35
+ - README.md
36
+ - Rakefile
37
+ - dreamcatcher.gemspec
38
+ - lib/dreamcatcher.rb
39
+ - lib/dreamcatcher/configuration.rb
40
+ - lib/dreamcatcher/exception_context.rb
41
+ - lib/dreamcatcher/logger_proxy.rb
42
+ - lib/dreamcatcher/mailer.rb
43
+ - lib/dreamcatcher/monitor.rb
44
+ - lib/dreamcatcher/rake.rb
45
+ - lib/dreamcatcher/templates/generic_exception.html.erb
46
+ - lib/dreamcatcher/templates/generic_exception.text.erb
47
+ - lib/dreamcatcher/templates/layout.html.erb
48
+ - lib/dreamcatcher/version.rb
49
+ - test/dreamcatcher_test.rb
50
+ - test/logger_proxy_test.rb
51
+ - test/test_helper.rb
52
+ homepage: https://github.com/wvanbergen/dreamcatcher
53
+ licenses: []
54
+ post_install_message:
55
+ rdoc_options: []
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ none: false
60
+ requirements:
61
+ - - ! '>='
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ requirements: []
71
+ rubyforge_project:
72
+ rubygems_version: 1.8.16
73
+ signing_key:
74
+ specification_version: 3
75
+ summary: Catch exceptions and send email notifications with context.
76
+ test_files:
77
+ - test/dreamcatcher_test.rb
78
+ - test/logger_proxy_test.rb
79
+ - test/test_helper.rb