exceptbox 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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +6 -0
- data/LICENSE.txt +21 -0
- data/README.md +170 -0
- data/lib/exceptbox/async_queue.rb +103 -0
- data/lib/exceptbox/breadcrumbs.rb +73 -0
- data/lib/exceptbox/cleaner.rb +79 -0
- data/lib/exceptbox/configuration.rb +165 -0
- data/lib/exceptbox/context.rb +53 -0
- data/lib/exceptbox/delivery.rb +116 -0
- data/lib/exceptbox/event.rb +138 -0
- data/lib/exceptbox/integrations/active_job.rb +50 -0
- data/lib/exceptbox/integrations/at_exit.rb +32 -0
- data/lib/exceptbox/integrations/error_subscriber.rb +37 -0
- data/lib/exceptbox/integrations/rack.rb +37 -0
- data/lib/exceptbox/integrations/railtie.rb +63 -0
- data/lib/exceptbox/integrations/sidekiq.rb +49 -0
- data/lib/exceptbox/request_data.rb +66 -0
- data/lib/exceptbox/stacktrace.rb +78 -0
- data/lib/exceptbox/tasks/exceptbox.rake +43 -0
- data/lib/exceptbox/version.rb +5 -0
- data/lib/exceptbox.rb +193 -0
- data/lib/generators/exceptbox/install/install_generator.rb +25 -0
- data/lib/generators/exceptbox/install/templates/exceptbox.rb.tt +33 -0
- metadata +67 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: d7dd82c21146c3c8a095ae61671626ab02a102ee76544575d73904ff0a918fb9
|
|
4
|
+
data.tar.gz: 2acaee834678f6b00ff8b848d6b48184bb36c1cfa41f70e6952f23c9c6fce177
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 94cc353e1ee4af8d0522a21e15c94c5fc85205e1646d401d4c8d56ca07cba633a780015d086f649124c746d98aa971ba9f0343d664cc385897bd461744386ab7
|
|
7
|
+
data.tar.gz: 0cb35d165fa0634b3b344cca93a353d6c51332f68cbbb5f7c79e2974d7af5cbec9d5034f800c45dc9d98c8cefdbe5f58bf0671ffe35a6ac154130c5030df7d3d
|
data/CHANGELOG.md
ADDED
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Inzamam Tahir
|
|
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 all
|
|
13
|
+
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 THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# Exceptbox for Ruby
|
|
2
|
+
|
|
3
|
+
Error monitoring for Ruby and Rails. Exceptbox reports exceptions from your
|
|
4
|
+
app to [Exceptbox](https://exceptbox.com), with the stack trace, the code
|
|
5
|
+
around it, the request, the user and the steps that led up to it.
|
|
6
|
+
|
|
7
|
+
- **Rails**: requests, ActiveJob, `Rails.error`, rake tasks and `rails runner`
|
|
8
|
+
- **Sidekiq** jobs
|
|
9
|
+
- **Rack** apps (Sinatra, Hanami, Roda...)
|
|
10
|
+
- **Plain Ruby** scripts
|
|
11
|
+
- No runtime dependencies. Never slows down or breaks your app: errors are
|
|
12
|
+
sent in batches on a background thread, and Exceptbox never raises.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
# Gemfile
|
|
18
|
+
gem "exceptbox"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bundle install
|
|
23
|
+
bin/rails generate exceptbox:install YOUR_API_KEY
|
|
24
|
+
bin/rails exceptbox:test # sends a test error to check the setup
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Your API key is in your project's settings in the Exceptbox dashboard. Keep
|
|
28
|
+
it out of git: set `EXCEPTBOX_API_KEY` in your environment.
|
|
29
|
+
|
|
30
|
+
That's it. Unhandled exceptions are now reported from production and staging.
|
|
31
|
+
|
|
32
|
+
## Reporting errors yourself
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
begin
|
|
36
|
+
PaymentGateway.charge(order)
|
|
37
|
+
rescue PaymentGateway::Error => e
|
|
38
|
+
Exceptbox.notify(e) # sent as a handled "warning"
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
Exceptbox.notify("Stock count went negative") # a message works too
|
|
42
|
+
|
|
43
|
+
Exceptbox.notify(e, severity: "info") do |event|
|
|
44
|
+
event.add_metadata(:order, id: order.id, total: order.total)
|
|
45
|
+
event.grouping_hash = "payment-gateway-timeout" # group these together
|
|
46
|
+
end
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`Rails.error.handle { ... }` and `Rails.error.report(e)` are reported too.
|
|
50
|
+
|
|
51
|
+
## Adding context
|
|
52
|
+
|
|
53
|
+
```ruby
|
|
54
|
+
class ApplicationController < ActionController::Base
|
|
55
|
+
before_action do
|
|
56
|
+
Exceptbox.set_user(current_user) # id, email, name
|
|
57
|
+
Exceptbox.add_metadata(:account, plan: current_account.plan)
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
Exceptbox.leave_breadcrumb("Charged card", { amount: 100 })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Controller actions, SQL queries, jobs enqueued and mails sent are recorded as
|
|
65
|
+
breadcrumbs automatically.
|
|
66
|
+
|
|
67
|
+
## Configuration
|
|
68
|
+
|
|
69
|
+
```ruby
|
|
70
|
+
# config/initializers/exceptbox.rb
|
|
71
|
+
Exceptbox.configure do |config|
|
|
72
|
+
config.api_key = ENV["EXCEPTBOX_API_KEY"]
|
|
73
|
+
|
|
74
|
+
config.enabled_release_stages = %w[production staging] # default
|
|
75
|
+
config.current_user = ->(env) { env["warden"]&.user } # Devise
|
|
76
|
+
config.filters += %w[iban national_id] # never sent
|
|
77
|
+
config.ignore_classes += %w[MyApp::ExpectedError]
|
|
78
|
+
config.app_version = ENV["GIT_SHA"] # auto-detected
|
|
79
|
+
|
|
80
|
+
config.before_notify do |event|
|
|
81
|
+
event.ignore! if event.exception.message.include?("Net::ReadTimeout")
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
| Setting | Default | |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `api_key` | `ENV["EXCEPTBOX_API_KEY"]` | Your project's API key |
|
|
89
|
+
| `endpoint` | `https://api.exceptbox.com` | `ENV["EXCEPTBOX_ENDPOINT"]` |
|
|
90
|
+
| `release_stage` | `Rails.env` / `RACK_ENV` | `ENV["EXCEPTBOX_RELEASE_STAGE"]` |
|
|
91
|
+
| `enabled_release_stages` | `production staging` | `nil` sends from every stage |
|
|
92
|
+
| `app_version` | auto | From common hosting env vars, a Capistrano `REVISION` file, or git |
|
|
93
|
+
| `filters` | passwords, tokens, keys, cookies, cards... | Plus your `filter_parameters`. Strings match any key containing them; Regexps work too |
|
|
94
|
+
| `ignore_classes` | 404s, bad requests | Never reported |
|
|
95
|
+
| `ignore_request_classes` | `ActiveRecord::RecordNotFound` | Ignored in requests only (a 404 there), reported from jobs |
|
|
96
|
+
| `send_code` | `true` | Send the lines of code around your frames |
|
|
97
|
+
| `breadcrumbs` / `max_breadcrumbs` | `true` / `25` | |
|
|
98
|
+
| `capture_handled_errors` | `true` | Report `Rails.error.handle` |
|
|
99
|
+
| `report_crashes` | `true` | Report the exception that ends a rake task or script |
|
|
100
|
+
| `async` / `batch_size` / `max_queue_size` | `true` / `10` / `100` | |
|
|
101
|
+
| `timeout` / `proxy` | `5` / `nil` | |
|
|
102
|
+
|
|
103
|
+
## Rack, Sinatra and plain Ruby
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
require "exceptbox"
|
|
107
|
+
Exceptbox.configure { |c| c.api_key = ENV["EXCEPTBOX_API_KEY"] }
|
|
108
|
+
|
|
109
|
+
use Exceptbox::Integrations::Rack # Rack / Sinatra
|
|
110
|
+
Exceptbox::Integrations::AtExit.install! # report crashes of a script
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## API
|
|
114
|
+
|
|
115
|
+
Events are sent to `POST {endpoint}/v1/events`:
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
Exceptbox-Api-Key: <project API key>
|
|
119
|
+
Exceptbox-Payload-Version: 1
|
|
120
|
+
Content-Type: application/json
|
|
121
|
+
Content-Encoding: gzip
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
```jsonc
|
|
125
|
+
{
|
|
126
|
+
"payload_version": 1,
|
|
127
|
+
"notifier": { "name": "exceptbox-ruby", "version": "0.1.0", "url": "..." },
|
|
128
|
+
"events": [{
|
|
129
|
+
"exceptions": [{ // outermost first, then its causes
|
|
130
|
+
"error_class": "NoMethodError",
|
|
131
|
+
"message": "undefined method 'total' for nil",
|
|
132
|
+
"stacktrace": [{
|
|
133
|
+
"file": "app/models/order.rb", // relative to the project root
|
|
134
|
+
"line": 42,
|
|
135
|
+
"method": "Order#charge",
|
|
136
|
+
"in_project": true,
|
|
137
|
+
"code": { "38": "...", "42": "...", "46": "..." }
|
|
138
|
+
}]
|
|
139
|
+
}],
|
|
140
|
+
"severity": "error", // error | warning | info
|
|
141
|
+
"handled": false,
|
|
142
|
+
"source": "request", // request, job, sidekiq, process, notify, application...
|
|
143
|
+
"context": "OrdersController#create",
|
|
144
|
+
"grouping_hash": null, // optional custom grouping
|
|
145
|
+
"timestamp": "2026-11-29T10:00:00.000Z",
|
|
146
|
+
"app": { "release_stage": "production", "version": "a1b2c3d4e5f6", "type": "rails" },
|
|
147
|
+
"device": { "hostname": "web-1", "runtime_versions": { "ruby": "3.4.5", "rails": "8.1.0" } },
|
|
148
|
+
"user": { "id": 7, "email": "ada@example.com", "name": "Ada Lovelace" },
|
|
149
|
+
"request": { "url": "...", "http_method": "POST", "params": {}, "headers": {},
|
|
150
|
+
"client_ip": "203.0.113.9", "referer": "...", "request_id": "..." },
|
|
151
|
+
"job": { "class": "InvoiceJob", "id": "...", "queue": "default", "attempt": 1, "arguments": [] },
|
|
152
|
+
"breadcrumbs": [{ "timestamp": "...", "type": "sql", "name": "SELECT ...", "metadata": {}, "duration_ms": 1.2 }],
|
|
153
|
+
"metadata": { "order": { "id": 42 } }
|
|
154
|
+
}]
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Responses: `202` accepted, `401` invalid API key, `413` too large, `429` over
|
|
159
|
+
quota or rate limited (the client pauses for `Retry-After` seconds).
|
|
160
|
+
|
|
161
|
+
## Development
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
bundle install
|
|
165
|
+
bundle exec rake test # unit tests (no Rails) + Rails integration tests
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
MIT
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Exceptbox
|
|
4
|
+
# One background thread that sends events in batches, so a failing request
|
|
5
|
+
# never waits on the network.
|
|
6
|
+
#
|
|
7
|
+
# - Bounded: past max_queue_size waiting events (an error storm), new ones
|
|
8
|
+
# are dropped instead of growing memory.
|
|
9
|
+
# - Batched: sends up to batch_size events per HTTP request.
|
|
10
|
+
# - Fork-safe: Puma/Unicorn workers each start their own thread lazily.
|
|
11
|
+
# - Flushed at exit, so events from a process that is shutting down are sent.
|
|
12
|
+
class AsyncQueue
|
|
13
|
+
SHUTDOWN_TIMEOUT = 5
|
|
14
|
+
|
|
15
|
+
def initialize(config)
|
|
16
|
+
@config = config
|
|
17
|
+
@mutex = Mutex.new
|
|
18
|
+
@queue = Queue.new
|
|
19
|
+
@thread = nil
|
|
20
|
+
@pid = nil
|
|
21
|
+
@pending = 0 # queued or being sent; flush waits for zero
|
|
22
|
+
@dropped = 0
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def push(event_hash)
|
|
26
|
+
ensure_thread!
|
|
27
|
+
|
|
28
|
+
if @queue.size >= @config.max_queue_size
|
|
29
|
+
@dropped += 1
|
|
30
|
+
@config.logger&.warn("Queue full, dropped #{@dropped} event(s) so far") if (@dropped % 100) == 1
|
|
31
|
+
return false
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
@mutex.synchronize { @pending += 1 }
|
|
35
|
+
@queue << event_hash
|
|
36
|
+
true
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Waits until everything queued has been sent (at exit, and in tests).
|
|
40
|
+
def flush(timeout: SHUTDOWN_TIMEOUT)
|
|
41
|
+
deadline = clock + timeout
|
|
42
|
+
sleep 0.01 until @mutex.synchronize { @pending.zero? } || clock > deadline
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Sends what is queued, then stops the thread (used by Exceptbox.reset!).
|
|
46
|
+
def shutdown(timeout: 1)
|
|
47
|
+
flush(timeout: timeout)
|
|
48
|
+
@thread&.kill
|
|
49
|
+
@thread = nil
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def size
|
|
53
|
+
@queue.size
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
def ensure_thread!
|
|
59
|
+
return if @pid == Process.pid && @thread&.alive?
|
|
60
|
+
|
|
61
|
+
@mutex.synchronize do
|
|
62
|
+
return if @pid == Process.pid && @thread&.alive?
|
|
63
|
+
|
|
64
|
+
if @pid && @pid != Process.pid # forked: the parent's events aren't ours
|
|
65
|
+
@queue = Queue.new
|
|
66
|
+
@pending = 0
|
|
67
|
+
end
|
|
68
|
+
@pid = Process.pid
|
|
69
|
+
@thread = Thread.new { run }
|
|
70
|
+
@thread.name = "exceptbox-delivery" if @thread.respond_to?(:name=)
|
|
71
|
+
@thread.report_on_exception = false
|
|
72
|
+
register_at_exit
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def run
|
|
77
|
+
loop do
|
|
78
|
+
batch = [@queue.pop]
|
|
79
|
+
begin
|
|
80
|
+
batch << @queue.pop(true) while batch.size < @config.batch_size
|
|
81
|
+
rescue ThreadError
|
|
82
|
+
# queue emptied while filling the batch
|
|
83
|
+
end
|
|
84
|
+
Delivery.deliver(batch, @config)
|
|
85
|
+
rescue StandardError => e
|
|
86
|
+
@config.logger&.error("Delivery thread error: #{e.class}: #{e.message}")
|
|
87
|
+
ensure
|
|
88
|
+
@mutex.synchronize { @pending -= batch.size } if batch
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def register_at_exit
|
|
93
|
+
return if @at_exit_registered
|
|
94
|
+
|
|
95
|
+
@at_exit_registered = true
|
|
96
|
+
at_exit { flush }
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def clock
|
|
100
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
module Exceptbox
|
|
6
|
+
# The steps leading up to an error: controller actions, SQL queries, jobs
|
|
7
|
+
# enqueued, mails sent, and anything you add with Exceptbox.leave_breadcrumb.
|
|
8
|
+
module Breadcrumbs
|
|
9
|
+
TYPES = %w[request sql job mail cache log manual].freeze
|
|
10
|
+
MAX_MESSAGE = 500
|
|
11
|
+
|
|
12
|
+
module_function
|
|
13
|
+
|
|
14
|
+
def leave(name, metadata = {}, type: "manual", duration: nil)
|
|
15
|
+
config = Exceptbox.configuration
|
|
16
|
+
return unless config.breadcrumbs
|
|
17
|
+
|
|
18
|
+
message = name.to_s
|
|
19
|
+
message = "#{message[0, MAX_MESSAGE]}…" if message.length > MAX_MESSAGE
|
|
20
|
+
Context.current.add_breadcrumb(
|
|
21
|
+
{
|
|
22
|
+
"timestamp" => Time.now.utc.iso8601(3),
|
|
23
|
+
"type" => TYPES.include?(type.to_s) ? type.to_s : "manual",
|
|
24
|
+
"name" => message,
|
|
25
|
+
"metadata" => metadata.nil? || metadata.empty? ? nil : metadata,
|
|
26
|
+
"duration_ms" => duration&.round(1)
|
|
27
|
+
}.compact,
|
|
28
|
+
config.max_breadcrumbs
|
|
29
|
+
)
|
|
30
|
+
rescue StandardError
|
|
31
|
+
nil
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Rails instrumentation (called by the Railtie).
|
|
35
|
+
def subscribe_to_rails!
|
|
36
|
+
return if @subscribed || !defined?(::ActiveSupport::Notifications)
|
|
37
|
+
|
|
38
|
+
@subscribed = true
|
|
39
|
+
|
|
40
|
+
subscribe("sql.active_record") do |event|
|
|
41
|
+
name = event.payload[:name].to_s
|
|
42
|
+
sql = event.payload[:sql].to_s
|
|
43
|
+
next if name == "SCHEMA" || sql.empty? || sql.start_with?("BEGIN", "COMMIT", "RELEASE", "SAVEPOINT")
|
|
44
|
+
|
|
45
|
+
leave(sql, { "name" => name.empty? ? nil : name, "cached" => event.payload[:cached] || nil }.compact,
|
|
46
|
+
type: "sql", duration: event.duration)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
subscribe("start_processing.action_controller") do |event|
|
|
50
|
+
p = event.payload
|
|
51
|
+
leave("#{p[:controller]}##{p[:action]}", { "method" => p[:method], "path" => p[:path] }.compact, type: "request")
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
subscribe("enqueue.active_job") do |event|
|
|
55
|
+
job = event.payload[:job]
|
|
56
|
+
leave("Enqueued #{job.class.name}", { "queue" => job.queue_name }, type: "job")
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
subscribe("deliver.action_mailer") do |event|
|
|
60
|
+
leave("Sent #{event.payload[:mailer]}", {}, type: "mail", duration: event.duration)
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def subscribe(name, &block)
|
|
65
|
+
::ActiveSupport::Notifications.subscribe(name) do |*args|
|
|
66
|
+
event = args.first.is_a?(::ActiveSupport::Notifications::Event) ? args.first : ::ActiveSupport::Notifications::Event.new(*args)
|
|
67
|
+
block.call(event)
|
|
68
|
+
rescue StandardError
|
|
69
|
+
nil
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Exceptbox
|
|
6
|
+
# Makes any data safe to send:
|
|
7
|
+
# - values of sensitive keys become "[FILTERED]"
|
|
8
|
+
# - live objects become strings (never serializes whole records)
|
|
9
|
+
# - long strings are truncated, deep or cyclic structures are cut off
|
|
10
|
+
module Cleaner
|
|
11
|
+
FILTERED = "[FILTERED]"
|
|
12
|
+
MAX_DEPTH = 8
|
|
13
|
+
MAX_STRING = 4_096
|
|
14
|
+
MAX_ITEMS = 200
|
|
15
|
+
|
|
16
|
+
QUERY_PAIR = /([^&;=]+)=([^&;#]*)/
|
|
17
|
+
|
|
18
|
+
module_function
|
|
19
|
+
|
|
20
|
+
def clean(value, filters, depth = 0, seen = {})
|
|
21
|
+
return "[DEPTH]" if depth > MAX_DEPTH
|
|
22
|
+
|
|
23
|
+
case value
|
|
24
|
+
when Hash
|
|
25
|
+
return "[RECURSION]" if seen[value.object_id]
|
|
26
|
+
|
|
27
|
+
seen[value.object_id] = true
|
|
28
|
+
out = value.first(MAX_ITEMS).each_with_object({}) do |(key, val), hash|
|
|
29
|
+
key = key.to_s
|
|
30
|
+
hash[key] = filtered_key?(key, filters) ? FILTERED : clean(val, filters, depth + 1, seen)
|
|
31
|
+
end
|
|
32
|
+
seen.delete(value.object_id)
|
|
33
|
+
out
|
|
34
|
+
when Array
|
|
35
|
+
return "[RECURSION]" if seen[value.object_id]
|
|
36
|
+
|
|
37
|
+
seen[value.object_id] = true
|
|
38
|
+
out = value.first(MAX_ITEMS).map { |val| clean(val, filters, depth + 1, seen) }
|
|
39
|
+
seen.delete(value.object_id)
|
|
40
|
+
out
|
|
41
|
+
when String then truncate(value.dup.force_encoding(Encoding::UTF_8).scrub)
|
|
42
|
+
when Symbol then value.to_s
|
|
43
|
+
when Numeric, true, false, nil then value.is_a?(Float) && !value.finite? ? value.to_s : value
|
|
44
|
+
when Time then value.utc.iso8601(3)
|
|
45
|
+
else
|
|
46
|
+
value.respond_to?(:iso8601) ? value.iso8601 : truncate(safe_to_s(value))
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def filtered_key?(key, filters)
|
|
51
|
+
down = key.downcase
|
|
52
|
+
Array(filters).any? do |filter|
|
|
53
|
+
filter.is_a?(Regexp) ? filter.match?(key) : down.include?(filter.to_s.downcase)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# "/reset?token=abc&lang=en" -> "/reset?token=[FILTERED]&lang=en"
|
|
58
|
+
def clean_url(url, filters)
|
|
59
|
+
return url if url.nil? || !url.include?("?")
|
|
60
|
+
|
|
61
|
+
base, rest = url.split("?", 2)
|
|
62
|
+
query, fragment = rest.split("#", 2)
|
|
63
|
+
query = query.gsub(QUERY_PAIR) { filtered_key?(Regexp.last_match(1), filters) ? "#{Regexp.last_match(1)}=#{FILTERED}" : Regexp.last_match(0) }
|
|
64
|
+
fragment ? "#{base}?#{query}##{fragment}" : "#{base}?#{query}"
|
|
65
|
+
rescue StandardError
|
|
66
|
+
url.to_s.split("?", 2).first
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def truncate(string)
|
|
70
|
+
string.length > MAX_STRING ? "#{string[0, MAX_STRING]}…[truncated]" : string
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def safe_to_s(value)
|
|
74
|
+
value.to_s
|
|
75
|
+
rescue StandardError
|
|
76
|
+
"[#{value.class}]"
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "logger"
|
|
4
|
+
require "socket"
|
|
5
|
+
|
|
6
|
+
module Exceptbox
|
|
7
|
+
# All settings, with defaults that work for a typical Rails app. Most apps
|
|
8
|
+
# only set the API key:
|
|
9
|
+
#
|
|
10
|
+
# Exceptbox.configure do |config|
|
|
11
|
+
# config.api_key = ENV["EXCEPTBOX_API_KEY"]
|
|
12
|
+
# end
|
|
13
|
+
class Configuration
|
|
14
|
+
DEFAULT_ENDPOINT = "https://api.exceptbox.com"
|
|
15
|
+
|
|
16
|
+
# Normal in a web app (404s, bad requests); never worth an alert.
|
|
17
|
+
DEFAULT_IGNORE_CLASSES = %w[
|
|
18
|
+
AbstractController::ActionNotFound
|
|
19
|
+
ActionController::BadRequest
|
|
20
|
+
ActionController::InvalidAuthenticityToken
|
|
21
|
+
ActionController::InvalidCrossOriginRequest
|
|
22
|
+
ActionController::MethodNotAllowed
|
|
23
|
+
ActionController::NotImplemented
|
|
24
|
+
ActionController::ParameterMissing
|
|
25
|
+
ActionController::RoutingError
|
|
26
|
+
ActionController::UnknownFormat
|
|
27
|
+
ActionController::UnknownHttpMethod
|
|
28
|
+
ActionDispatch::Http::MimeNegotiation::InvalidType
|
|
29
|
+
ActionDispatch::Http::Parameters::ParseError
|
|
30
|
+
Rack::QueryParser::InvalidParameterError
|
|
31
|
+
Rack::QueryParser::ParameterTypeError
|
|
32
|
+
Sinatra::NotFound
|
|
33
|
+
].freeze
|
|
34
|
+
|
|
35
|
+
# A 404 in a web request, but a real failure in a job or script.
|
|
36
|
+
DEFAULT_IGNORE_REQUEST_CLASSES = %w[ActiveRecord::RecordNotFound].freeze
|
|
37
|
+
|
|
38
|
+
# Keys whose values are replaced with "[FILTERED]" anywhere in the payload
|
|
39
|
+
# (params, headers, metadata, job arguments). Matched case-insensitively as
|
|
40
|
+
# substrings, so "user_password" and "X-Api-Token" are filtered too.
|
|
41
|
+
DEFAULT_FILTERS = %w[
|
|
42
|
+
password passwd secret token api_key apikey access_key authorization
|
|
43
|
+
cookie session csrf credit_card card_number cvv cvc ssn private_key
|
|
44
|
+
].freeze
|
|
45
|
+
|
|
46
|
+
# --- Where to send -------------------------------------------------------
|
|
47
|
+
attr_accessor :api_key, :endpoint, :timeout, :proxy
|
|
48
|
+
|
|
49
|
+
# --- What to send --------------------------------------------------------
|
|
50
|
+
# The stage this app runs in ("production", "staging"...) and the stages
|
|
51
|
+
# that report. Errors from other stages (development, test) are dropped.
|
|
52
|
+
attr_accessor :release_stage, :enabled_release_stages
|
|
53
|
+
attr_accessor :app_version, :app_type, :hostname
|
|
54
|
+
attr_accessor :project_root # frames under it are "your code"
|
|
55
|
+
attr_accessor :send_code # send source lines around your frames
|
|
56
|
+
attr_accessor :ignore_classes, :ignore_request_classes
|
|
57
|
+
attr_accessor :filters # see DEFAULT_FILTERS
|
|
58
|
+
attr_accessor :max_breadcrumbs, :breadcrumbs
|
|
59
|
+
attr_accessor :capture_handled_errors # Rails.error.handle / report
|
|
60
|
+
attr_accessor :report_crashes # exception that ends a rake task / script
|
|
61
|
+
|
|
62
|
+
# ->(context) { user }: context is the Rack env of the request. A plain
|
|
63
|
+
# Hash ({ id:, email:, name: }) or any object with those methods works.
|
|
64
|
+
attr_accessor :current_user
|
|
65
|
+
|
|
66
|
+
# --- How to send ---------------------------------------------------------
|
|
67
|
+
attr_accessor :async, :max_queue_size, :batch_size
|
|
68
|
+
attr_accessor :logger
|
|
69
|
+
|
|
70
|
+
# Callables run before each event is sent: ->(event) { ... }. They can
|
|
71
|
+
# change the event (event.add_metadata, event.severity = ...) or drop it
|
|
72
|
+
# by returning false / calling event.ignore!.
|
|
73
|
+
attr_reader :before_notify_callbacks
|
|
74
|
+
|
|
75
|
+
def initialize
|
|
76
|
+
@api_key = ENV["EXCEPTBOX_API_KEY"]
|
|
77
|
+
@endpoint = ENV.fetch("EXCEPTBOX_ENDPOINT", DEFAULT_ENDPOINT)
|
|
78
|
+
@timeout = 5
|
|
79
|
+
@proxy = nil
|
|
80
|
+
@release_stage = ENV["EXCEPTBOX_RELEASE_STAGE"] || detect_release_stage
|
|
81
|
+
@enabled_release_stages = %w[production staging]
|
|
82
|
+
@app_version = nil
|
|
83
|
+
@app_type = nil
|
|
84
|
+
@hostname = safe_hostname
|
|
85
|
+
@project_root = nil
|
|
86
|
+
@send_code = true
|
|
87
|
+
@ignore_classes = DEFAULT_IGNORE_CLASSES.dup
|
|
88
|
+
@ignore_request_classes = DEFAULT_IGNORE_REQUEST_CLASSES.dup
|
|
89
|
+
@filters = DEFAULT_FILTERS.dup
|
|
90
|
+
@max_breadcrumbs = 25
|
|
91
|
+
@breadcrumbs = true
|
|
92
|
+
@capture_handled_errors = true
|
|
93
|
+
@report_crashes = true
|
|
94
|
+
@current_user = nil
|
|
95
|
+
@async = true
|
|
96
|
+
@max_queue_size = 100
|
|
97
|
+
@batch_size = 10
|
|
98
|
+
@logger = Logger.new($stderr, progname: "Exceptbox")
|
|
99
|
+
@before_notify_callbacks = []
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def before_notify(callable = nil, &block)
|
|
103
|
+
@before_notify_callbacks << (callable || block)
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def app_version
|
|
107
|
+
@app_version ||= detect_app_version
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def project_root
|
|
111
|
+
@project_root ||= (defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root&.to_s) || Dir.pwd
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Sends only when there's a key and this stage is enabled.
|
|
115
|
+
def notify_release_stage?
|
|
116
|
+
stages = enabled_release_stages
|
|
117
|
+
stages.nil? || Array(stages).map(&:to_s).include?(release_stage.to_s)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def valid_api_key?
|
|
121
|
+
api_key.is_a?(String) && !api_key.strip.empty?
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def ignored?(exception, request: false)
|
|
125
|
+
names = exception.class.ancestors.map(&:name)
|
|
126
|
+
list = Array(ignore_classes)
|
|
127
|
+
list += Array(ignore_request_classes) if request
|
|
128
|
+
list.any? { |klass| names.include?(klass.to_s) }
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def events_url
|
|
132
|
+
"#{endpoint.to_s.chomp('/')}/v1/events"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
private
|
|
136
|
+
|
|
137
|
+
def detect_release_stage
|
|
138
|
+
(defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.to_s) ||
|
|
139
|
+
ENV["RACK_ENV"] || ENV["RAILS_ENV"] || "production"
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Deployed version: env vars set by common hosts, Capistrano's REVISION
|
|
143
|
+
# file, then git.
|
|
144
|
+
def detect_app_version
|
|
145
|
+
from_env = ENV.values_at(
|
|
146
|
+
"EXCEPTBOX_APP_VERSION", "HEROKU_SLUG_COMMIT", "RENDER_GIT_COMMIT", "SOURCE_VERSION", "GIT_COMMIT", "KAMAL_VERSION"
|
|
147
|
+
).compact.first
|
|
148
|
+
return from_env[0, 12] if from_env
|
|
149
|
+
|
|
150
|
+
revision = File.join(project_root, "REVISION")
|
|
151
|
+
return File.read(revision).strip[0, 12] if File.file?(revision)
|
|
152
|
+
|
|
153
|
+
sha = `git -C #{project_root.to_s.inspect} rev-parse HEAD 2>/dev/null`.strip
|
|
154
|
+
sha.empty? ? nil : sha[0, 12]
|
|
155
|
+
rescue StandardError
|
|
156
|
+
nil
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def safe_hostname
|
|
160
|
+
Socket.gethostname
|
|
161
|
+
rescue StandardError
|
|
162
|
+
nil
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Exceptbox
|
|
4
|
+
# Per-request / per-job state: user, metadata, breadcrumbs, the Rack env.
|
|
5
|
+
#
|
|
6
|
+
# Stored in Thread.current[], which Ruby keeps per fiber, so concurrent
|
|
7
|
+
# requests (threads in Puma, fibers in Falcon) never see each other's data.
|
|
8
|
+
# The integrations clear it at the start and end of every request and job.
|
|
9
|
+
class Context
|
|
10
|
+
KEY = :__exceptbox_context
|
|
11
|
+
|
|
12
|
+
attr_accessor :env, :job, :user, :context_name
|
|
13
|
+
attr_reader :metadata, :breadcrumbs
|
|
14
|
+
|
|
15
|
+
def self.current
|
|
16
|
+
Thread.current[KEY] ||= new
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def self.clear!
|
|
20
|
+
Thread.current[KEY] = nil
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Runs the block with a fresh context and restores the previous one after
|
|
24
|
+
# (a job run inline inside a request must not wipe the request's data).
|
|
25
|
+
def self.isolate
|
|
26
|
+
previous = Thread.current[KEY]
|
|
27
|
+
Thread.current[KEY] = new
|
|
28
|
+
yield
|
|
29
|
+
ensure
|
|
30
|
+
Thread.current[KEY] = previous
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def initialize
|
|
34
|
+
@metadata = {}
|
|
35
|
+
@breadcrumbs = []
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def add_metadata(section, data)
|
|
39
|
+
(@metadata[section.to_s] ||= {}).merge!(stringify(data))
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def add_breadcrumb(crumb, max)
|
|
43
|
+
@breadcrumbs << crumb
|
|
44
|
+
@breadcrumbs.shift while @breadcrumbs.size > max
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private
|
|
48
|
+
|
|
49
|
+
def stringify(data)
|
|
50
|
+
data.to_h.each_with_object({}) { |(k, v), out| out[k.to_s] = v }
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|