forked from rollbar/rollbar-gem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollbar.rb
661 lines (549 loc) · 18.3 KB
/
rollbar.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
require 'net/https'
require 'socket'
require 'thread'
require 'uri'
require 'multi_json'
begin
require 'securerandom'
rescue LoadError
end
require 'rollbar/version'
require 'rollbar/configuration'
require 'rollbar/request_data_extractor'
require 'rollbar/exception_reporter'
require 'rollbar/active_record_extension' if defined?(ActiveRecord)
require 'rollbar/util'
require 'rollbar/railtie' if defined?(Rails)
require 'rollbar/delay/girl_friday'
require 'rollbar/delay/thread'
unless ''.respond_to? :encode
require 'iconv'
end
module Rollbar
MAX_PAYLOAD_SIZE = 128 * 1024 #128kb
class << self
attr_writer :configuration
attr_accessor :last_report
@file_semaphore = Mutex.new
# Similar to configure below, but used only internally within the gem
# to configure it without initializing any of the third party hooks
def preconfigure
yield(configuration)
end
# Configures the gem.
#
# Call on app startup to set the `access_token` (required) and other config params.
# In a Rails app, this is called by `config/initializers/rollbar.rb` which is generated
# with `rails generate rollbar access-token-here`
#
# @example
# Rollbar.configure do |config|
# config.access_token = 'abcdefg'
# end
def configure
# if configuration.enabled has not been set yet (is still 'nil'), set to true.
configuration.enabled = true if configuration.enabled.nil?
yield(configuration)
require_hooks
end
def reconfigure
@configuration = Configuration.new
@configuration.enabled = true
yield(configuration)
end
def unconfigure
@configuration = nil
end
# Returns the configuration object.
#
# @return [Rollbar::Configuration] The configuration object
def configuration
@configuration ||= Configuration.new
end
# Reports an exception to Rollbar. Returns the exception data hash.
#
# @example
# begin
# foo = bar
# rescue => e
# Rollbar.report_exception(e)
# end
#
# @param exception [Exception] The exception object to report
# @param request_data [Hash] Data describing the request. Should be the result of calling
# `rollbar_request_data`.
# @param person_data [Hash] Data describing the affected person. Should be the result of calling
# `rollbar_person_data`
def report_exception(exception, request_data = nil, person_data = nil, level = nil)
if person_data
person_id = person_data[Rollbar.configuration.person_id_method.to_sym]
return 'ignored' if configuration.ignored_person_ids.include?(person_id)
end
return 'disabled' unless configuration.enabled
return 'ignored' if ignored?(exception)
data = exception_data(exception, level ? level : filtered_level(exception))
attach_request_data(data, request_data) if request_data
data[:person] = person_data if person_data
@last_report = data
payload = build_payload(data)
schedule_payload(payload)
log_instance_link(data)
data
rescue Exception => e
report_internal_error(e)
'error'
end
# Reports an arbitrary message to Rollbar
#
# @example
# Rollbar.report_message("User login failed", 'info', :user_id => 123)
#
# @param message [String] The message body. This will be used to identify the message within
# Rollbar. For best results, avoid putting variables in the message body; pass them as
# `extra_data` instead.
# @param level [String] The level. One of: 'critical', 'error', 'warning', 'info', 'debug'
# @param extra_data [Hash] Additional data to include alongside the body. Don't use 'body' as
# it is reserved.
def report_message(message, level = 'info', extra_data = {})
return 'disabled' unless configuration.enabled
data = message_data(message, level, extra_data)
@last_report = data
payload = build_payload(data)
schedule_payload(payload)
log_instance_link(data)
data
rescue Exception => e
report_internal_error(e)
'error'
end
# Reports an arbitrary message to Rollbar with request and person data
#
# @example
# Rollbar.report_message_with_request("User login failed", 'info', rollbar_request_data, rollbar_person_data, :foo => 'bar')
#
# @param message [String] The message body. This will be used to identify the message within
# Rollbar. For best results, avoid putting variables in the message body; pass them as
# `extra_data` instead.
# @param level [String] The level. One of: 'critical', 'error', 'warning', 'info', 'debug'
# @param request_data [Hash] Data describing the request. Should be the result of calling
# `rollbar_request_data`.
# @param person_data [Hash] Data describing the affected person. Should be the result of calling
# `rollbar_person_data`
# @param extra_data [Hash] Additional data to include alongside the body. Don't use 'body' as
# it is reserved.
def report_message_with_request(message, level = 'info', request_data = nil, person_data = nil, extra_data = {})
return 'disabled' unless configuration.enabled
data = message_data(message, level, extra_data)
attach_request_data(data, request_data) if request_data
data[:person] = person_data if person_data
@last_report = data
payload = build_payload(data)
schedule_payload(payload)
log_instance_link(data)
data
rescue => e
report_internal_error(e)
'error'
end
# Turns off reporting for the given block.
#
# @example
# Rollbar.silenced { raise }
#
# @yield Block which exceptions won't be reported.
def silenced
begin
yield
rescue => e
e.instance_variable_set(:@_rollbar_do_not_report, true)
raise
end
end
def process_payload(payload)
begin
if configuration.write_to_file
write_payload(payload)
else
send_payload(payload)
end
rescue => e
log_error "[Rollbar] Error processing payload: #{e}"
end
end
# wrappers around logger methods
def log_error(message)
begin
logger.error message
rescue => e
puts "[Rollbar] Error logging error:"
puts "[Rollbar] #{message}"
end
end
def log_info(message)
begin
logger.info message
rescue => e
puts "[Rollbar] Error logging info:"
puts "[Rollbar] #{message}"
end
end
def log_warning(message)
begin
logger.warn message
rescue => e
puts "[Rollbar] Error logging warning:"
puts "[Rollbar] #{message}"
end
end
def log_debug(message)
begin
logger.debug message
rescue => e
puts "[Rollbar] Error logging debug"
puts "[Rollbar] #{message}"
end
end
def default_async_handler
return Rollbar::Delay::GirlFriday if defined?(GirlFriday)
Rollbar::Delay::Thread
end
private
def attach_request_data(payload, request_data)
if request_data[:route]
route = request_data[:route]
# make sure route is a hash built by RequestDataExtractor in rails apps
if route.is_a?(Hash) and not route.empty?
payload[:context] = "#{request_data[:route][:controller]}" + '#' + "#{request_data[:route][:action]}"
end
end
request_data[:env].reject!{|k, v| v.is_a?(IO) } if request_data[:env]
payload[:request] = request_data
end
def require_hooks()
if defined?(Delayed) && defined?(Delayed::Worker) && configuration.delayed_job_enabled
require 'rollbar/delayed_job'
Rollbar::Delayed::wrap_worker
end
require 'rollbar/sidekiq' if defined?(Sidekiq)
require 'rollbar/goalie' if defined?(Goalie)
require 'rollbar/rack' if defined?(Rack)
require 'rollbar/rake' if defined?(Rake)
require 'rollbar/better_errors' if defined?(BetterErrors)
end
def log_instance_link(data)
log_info "[Rollbar] Details: #{configuration.web_base}/instance/uuid?uuid=#{data[:uuid]} (only available if report was successful)"
end
def ignored?(exception)
if filtered_level(exception) == 'ignore'
return true
end
if exception.instance_variable_get(:@_rollbar_do_not_report)
return true
end
false
end
def filtered_level(exception)
filter = configuration.exception_level_filters[exception.class.name]
if filter.respond_to?(:call)
filter.call(exception)
else
filter
end
end
def message_data(message, level, extra_data)
data = base_data(level)
data[:body] = {
:message => {
:body => message.to_s
}
}
data[:body][:message].merge!(extra_data)
data[:server] = server_data
data
end
def exception_data(exception, force_level = nil)
data = base_data
data[:level] = force_level if force_level
# parse backtrace
if exception.backtrace.respond_to?( :map )
frames = exception.backtrace.map { |frame|
# parse the line
match = frame.match(/(.*):(\d+)(?::in `([^']+)')?/)
if match
{ :filename => match[1], :lineno => match[2].to_i, :method => match[3] }
else
{ :filename => "<unknown>", :lineno => 0, :method => frame }
end
}
# reverse so that the order is as rollbar expects
frames.reverse!
else
frames = []
end
data[:body] = {
:trace => {
:frames => frames,
:exception => {
:class => exception.class.name,
:message => exception.message
}
}
}
data[:server] = server_data
data
end
def logger
# init if not set
unless configuration.logger
configuration.logger = configuration.default_logger.call
end
configuration.logger
end
def write_payload(payload)
if configuration.use_async
@file_semaphore.synchronize {
do_write_payload(payload)
}
else
do_write_payload(payload)
end
end
def do_write_payload(payload)
log_info '[Rollbar] Writing payload to file'
begin
unless @file
@file = File.open(configuration.filepath, "a")
end
@file.puts payload
@file.flush
log_info "[Rollbar] Success"
rescue IOError => e
log_error "[Rollbar] Error opening/writing to file: #{e}"
end
end
def send_payload_using_eventmachine(payload)
body = dump_payload(payload)
headers = { 'X-Rollbar-Access-Token' => payload['access_token'] }
req = EventMachine::HttpRequest.new(configuration.endpoint).post(:body => body, :head => headers)
req.callback do
if req.response_header.status == 200
log_info '[Rollbar] Success'
else
log_warning "[Rollbar] Got unexpected status code from Rollbar.io api: #{req.response_header.status}"
log_info "[Rollbar] Response: #{req.response}"
end
end
req.errback do
log_warning "[Rollbar] Call to API failed, status code: #{req.response_header.status}"
log_info "[Rollbar] Error's response: #{req.response}"
end
end
def send_payload(payload)
log_info '[Rollbar] Sending payload'
payload = MultiJson.load(payload) if payload.is_a?(String)
if configuration.use_eventmachine
send_payload_using_eventmachine(payload)
return
end
body = dump_payload(payload)
uri = URI.parse(configuration.endpoint)
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = configuration.request_timeout
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Post.new(uri.request_uri)
request.body = body
request.add_field('X-Rollbar-Access-Token', payload['access_token'])
response = http.request(request)
if response.code == '200'
log_info '[Rollbar] Success'
else
log_warning "[Rollbar] Got unexpected status code from Rollbar api: #{response.code}"
log_info "[Rollbar] Response: #{response.body}"
end
end
def schedule_payload(payload)
return if payload.nil?
log_info '[Rollbar] Scheduling payload'
if configuration.use_async
process_async_payload(payload)
else
process_payload(payload)
end
end
def process_async_payload(payload)
configuration.async_handler ||= default_async_handler
configuration.async_handler.call(payload)
rescue
if configuration.failover_handlers.empty?
log_error '[Rollbar] Async handler failed, and there are no failover handlers configured. See the docs for "failover_handlers"'
return
end
async_failover(payload)
end
def async_failover(payload)
log_warning '[Rollbar] Primary async handler failed. Trying failovers...'
failover_handlers = configuration.failover_handlers
failover_handlers.each do |handler|
begin
handler.call(payload)
rescue
next unless handler == failover_handlers.last
log_error "[Rollbar] All failover handlers failed while processing payload: #{MultiJson.dump(payload)}"
end
end
end
def build_payload(data)
payload = {
'access_token' => configuration.access_token,
'data' => data
}
enforce_valid_utf8(payload)
payload
end
def dump_payload(payload)
result = MultiJson.dump(payload)
# Try to truncate strings in the payload a few times if the payload is too big
original_size = result.bytesize
if original_size > MAX_PAYLOAD_SIZE
thresholds = [1024, 512, 256]
thresholds.each_with_index do |threshold, i|
new_payload = payload.clone
truncate_payload(new_payload, threshold)
result = MultiJson.dump(new_payload)
if result.bytesize <= MAX_PAYLOAD_SIZE
break
elsif i == thresholds.length - 1
final_size = result.bytesize
send_failsafe("Could not send payload due to it being too large after truncating attempts. Original size: #{original_size} Final size: #{final_size}", nil)
log_error "[Rollbar] Payload too large to be sent: #{MultiJson.dump(payload)}"
return
end
end
end
result
end
def base_data(level = 'error')
config = configuration
environment = config.environment
if environment.nil? || environment.empty?
environment = 'unspecified'
end
data = {
:timestamp => Time.now.to_i,
:environment => environment,
:level => level,
:language => 'ruby',
:framework => config.framework,
:project_package_paths => config.project_gem_paths,
:notifier => {
:name => 'rollbar-gem',
:version => VERSION
}
}
if config.code_version
data[:code_version] = config.code_version
end
if defined?(SecureRandom) and SecureRandom.respond_to?(:uuid)
data[:uuid] = SecureRandom.uuid
end
unless config.custom_data_method.nil?
data[:custom] = config.custom_data_method.call
end
data
end
def server_data
config = configuration
data = {
:host => Socket.gethostname
}
data[:root] = config.root.to_s if config.root
data[:branch] = config.branch if config.branch
data
end
# Reports an internal error in the Rollbar library. This will be reported within the configured
# Rollbar project. We'll first attempt to provide a report including the exception traceback.
# If that fails, we'll fall back to a more static failsafe response.
def report_internal_error(exception)
log_error "[Rollbar] Reporting internal error encountered while sending data to Rollbar."
begin
data = exception_data(exception, 'error')
rescue => e
send_failsafe("error in exception_data", e)
return
end
data[:internal] = true
begin
payload = build_payload(data)
rescue => e
send_failsafe("error in build_payload", e)
return
end
begin
schedule_payload(payload)
rescue => e
send_failsafe("error in schedule_payload", e)
return
end
begin
log_instance_link(data)
rescue => e
send_failsafe("error logging instance link", e)
return
end
end
def send_failsafe(message, exception)
log_error "[Rollbar] Sending failsafe response due to #{message}."
if exception
begin
log_error "[Rollbar] #{exception.class.name}: #{exception}"
rescue => e
end
end
config = configuration
environment = config.environment
failsafe_data = {
:level => 'error',
:environment => "#{environment}",
:body => { :message => { :body => "Failsafe from rollbar-gem: #{message}" } },
:notifier => { :name => 'rollbar-gem', :version => "#{VERSION}" },
:internal => true,
:failsafe => true
}
failsafe_payload = build_payload(failsafe_data)
begin
schedule_payload(failsafe_payload)
rescue => e
log_error "[Rollbar] Error sending failsafe : #{e}"
end
end
def enforce_valid_utf8(payload)
normalizer = Proc.new do |value|
if value.is_a?(String)
if value.respond_to? :encode
value.encode('UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '')
else
::Iconv.conv('UTF-8//IGNORE', 'UTF-8', value)
end
else
value
end
end
Rollbar::Util::iterate_and_update(payload, normalizer)
end
def truncate_payload(payload, byte_threshold)
truncator = Proc.new do |value|
if value.is_a?(String) and value.bytesize > byte_threshold
Rollbar::Util::truncate(value, byte_threshold)
else
value
end
end
Rollbar::Util::iterate_and_update(payload, truncator)
end
end
end
# Setting Ratchetio as an alias to Rollbar for ratchetio-gem backwards compatibility
Ratchetio = Rollbar