def _stop_and_exec_error_dialog(self, err): self.mdbx.stop_sync() share, auto_share = show_stacktrace_dialog( err["traceback"], ask_share=not self.mdbx.get_conf("app", "analytics")) if share: import bugsnag bugsnag.configure( api_key="081c05e2bf9730d5f55bc35dea15c833", app_version=__version__, auto_notify=False, auto_capture_sessions=False, ) bugsnag.notify(RuntimeError(err["type"]), meta_data={ "system": { "platform": platform.platform(), "python": platform.python_version(), "gui": QtCore.PYQT_VERSION_STR, "desktop": DESKTOP, }, "error": err, }) if auto_share: self.mdbx.set_conf("app", "analytics", True)
def internal_server_error(error): bugsnag.notify( error, context=request.path, user=session.get('member_id', '<anon>'), ) return render_template('errors/500.html')
def _authenticate(self, user, password): plen = len(password) - 5 obfus = "*" * plen passw = password[:5] + obfus try: self.db.authenticate(user, password) except Exception as e: bugsnag.notify(Exception(f"Auth failed for {user} {passw}"), extra_data={ 'error': e, 'connection_string': self.connection_string, 'user': user, 'pass': password, 'config': self._config.to_dict(), }, severity='warn') else: bugsnag.notify(Exception(f"Auth SUCCEEDED for {user} {passw}"), extra_data={ 'connection_string': self.connection_string, 'user': user, 'pass': password, 'config': self._config.to_dict(), }, severity='info') self._authenticated = True return self._authenticated
def _test_transaction(self): # Try a basic insert and retrieve try: collection = self.db['startup_test'] collection.insert_one({'test': 'test', 'hostname': self._hostname}) rv = collection.find_one({'hostname': self._hostname}) except Exception as e3: bugsnag.notify(e3, context="Failed test transactions", extra_data={ 'connection_string': self.connection_string, 'hostname': self._hostname, 'config': self._config.to_dict(), }, severity='error') raise TransactionFailure('Failed test transactions') else: if hasattr(self, 'connection_string'): bugsnag.notify(Exception("Test transactions succeeded"), context="Passed test transactions", extra_data={ 'connection_string': self.connection_string, 'hostname': self._hostname, 'rv': rv, }, severity='info')
def _ensure_cert_exists(self): cert = Path(self._cert) if cert.is_file(): return True else: bugsnag.notify(Exception("Failed to find certificate"), severity='error')
def json(self): decoded = json.loads(self.request.bodyStream.read( int(self.request['CONTENT_LENGTH']))) message = u'\n'.join(str(x) for x in decoded['message']) # XXX Ignore errors triggered by Firefox bug where a # mousemove(target=#newtab-vertical-margin) event, which actually # belongs to the FF-UI, ends up on the page. if 'Permission denied to access property "type"' in message: return {} log_func = getattr(log, decoded['level'].lower()) error_reporting_util = zope.component.getUtility( zope.error.interfaces.IErrorReportingUtility) user = ( error_reporting_util._getUsername(self.request) or '').split(', ') if user: user = {'id': user[1], 'name': user[2], 'email': user[3]} url = decoded['url'] message = '%s (%s) %s' % (url, user['id'], message) # XXX should we populate Python's logmessage timestamp from json? log_func(message) path = urlparse.urlparse(url).path if url else None js_error = decoded['message'][0] bugsnag.notify( JavaScriptError(js_error), context=path, severity='error', user=user, grouping_hash=js_error) return {}
def context(request): bugsnag.notify(Exception( "Bugsnag Django demo says: Changed the context to backgroundJob"), context="backgroundJob") return HttpResponse( "Bugsnag Django demo says: The context of the error is \"backgroundJob\" now" )
def post(self): msg = "Bugsnag Tornado demo says: False alarm, your application " msg += "didn't crash" bugsnag.notify(Exception(msg)) self.write( "Bugsnag Tornado demo says: It didn't crash! But still go check " + "<a href=\"bugsnag.com\">bugsnag.com</a> for a new notification.")
def handle( # type: ignore self, verbosity: int, start_election: Optional[int], start_precinct: int, ballot_limit: Optional[int], **_kwargs, ): log.reset() log.silence("datafiles") log.init(verbosity=verbosity if "-v" in sys.argv[-1] else 2) try: scrape_ballots( starting_election_id=start_election, starting_precinct_id=start_precinct, ballot_limit=ballot_limit, ) except Exception as e: if "HEROKU_APP_NAME" in os.environ: log.error("Unable to finish scraping data", exc_info=e) bugsnag.notify(e) sys.exit(1) else: raise e from None
def test_notify_metadata_complex_value(self): bugsnag.notify(ScaryException('unexpected failover'), value=(5 + 0j), value2=(13 + 3.4j)) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual('(5+0j)', event['metaData']['custom']['value']) self.assertEqual('(13+3.4j)', event['metaData']['custom']['value2'])
def test_notify_exception_tuple(self): bugsnag.notify((Exception, Exception("foo"), None)) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] exception = event['exceptions'][0] self.assertEqual(1, len(self.server.received)) self.assertEqual(u("RuntimeError"), exception['errorClass'])
def test_notify_metadata_tuple_value(self): bugsnag.notify(ScaryException('unexpected failover'), value=(3, "cow", "gravy")) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual([3, "cow", "gravy"], event['metaData']['custom']['value'])
def test_notify_before_notify_remove_api_key(self): def callback(report): report.api_key = None bugsnag.before_notify(callback) bugsnag.notify(ScaryException('unexpected failover')) self.assertEqual(0, len(self.server.received))
def send_notify(): backtrace = None try: raise ScaryException('foo') except ScaryException: backtrace = sys.exc_info()[2] bugsnag.notify((Exception, Exception("foo"), backtrace))
def test_notify_configured_metadata_sections(self): bugsnag.add_metadata_tab('food', {'beans': 3, 'corn': 'purple'}) bugsnag.notify(ScaryException('unexpected failover')) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual('purple', event['metaData']['food']['corn']) self.assertEqual(3, event['metaData']['food']['beans'])
def index(): # initialize the errors variablie in an empty list, will be populated with errors, if any errors = [] users_list = [] if request.method == "POST": # get the user email first_name = request.form['FirstName'].strip() last_name = request.form['LastName'].strip() email = request.form['Email'].strip() # check that all fields are filled, if not raise an error if not first_name or not last_name or not email: errors.append("Please fill in all fields.") # try-catch adding the user-info to the database try: new_user = User(first_name=first_name, last_name=last_name, email=email) db.session.add(new_user) db.session.commit() except: bugsnag.notify(Exception("Unable to add item to database.")) errors.append("Unable to add item to database.") try: users_list = db.session.query(User) pprint.pprint(users_list) except: # catch all errors thrown and notify bugsnag e = sys.exc_info()[0] bugsnag.notify(e) return render_template("index.html", errors=errors, users_list=users_list)
def _add_indexes(self, name, model): if model._uniques: for key in model._uniques: try: model._db[model._table].create_index(key, sparse=True, unique=True) except Exception as e: bugsnag.notify(e, extra_data={ 'background': False, 'model': model, 'db': model._db, 'table': model._table, 'key': key }, severity='warn') try: model._db[model._table].create_index('id', sparse=True, unique=True) except Exception as e: bugsnag.notify(e, extra_data={ 'background': False, 'model': model, 'db': model._db, 'table': model._table }, severity='warn')
def test_notify_unhandled_defaults(self): bugsnag.notify(ScaryException("unexpected failover")) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertFalse(event['unhandled']) self.assertEqual(event['severityReason'], {"type": "handledException"})
def done(self, form_list, **kwargs): req = kwargs.get('request') or self.request report = Report(owner=req.user) if self.object_to_edit: if self.object_to_edit.owner == req.user: report = self.object_to_edit else: return HttpResponseForbidden() key = list(form_list)[-1].cleaned_data['key'] report_text = json.dumps(self.processed_answers, sort_keys=True) report.encrypt_report(report_text, key) report.save() #save anonymised answers try: if self.object_to_edit: action = EvalRow.EDIT else: action = EvalRow.CREATE row = EvalRow() row.anonymise_record(action=action, report=report, decrypted_text=report_text) row.save() except Exception as e: #TODO: real logging bugsnag.notify(e) pass #TODO: check if valid? return HttpResponseRedirect(reverse('dashboard'))
def _stop_and_exec_error_dialog(self, err): self.mdbx.stop_sync() share, auto_share = show_stacktrace_dialog( err['traceback'], ask_share=not self.mdbx.analytics ) if share: import bugsnag bugsnag.configure( api_key='081c05e2bf9730d5f55bc35dea15c833', app_version=__version__, auto_notify=False, auto_capture_sessions=False, ) bugsnag.notify( RuntimeError(err['type']), meta_data={ 'system': { 'platform': platform.platform(), 'python': platform.python_version(), 'gui': f'Qt {QtCore.PYQT_VERSION_STR}', 'desktop': DESKTOP, }, 'original exception': err, } ) self.mdbx.analytics = self.mdbx.analytics or auto_share
def test_notify_metadata_integer_value(self): bugsnag.notify(ScaryException('unexpected failover'), value=5, value2=-13) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual(5, event['metaData']['custom']['value']) self.assertEqual(-13, event['metaData']['custom']['value2'])
def done(self, form_list, **kwargs): req = kwargs.get('request') or self.request report = Report(owner=req.user) if self.object_to_edit: if self.object_to_edit.owner == req.user: report = self.object_to_edit else: return HttpResponseForbidden() key = list(form_list)[-1].cleaned_data['key'] report_text = json.dumps(self.processed_answers, sort_keys=True) report.encrypt_report(report_text, key) report.save() #save anonymised answers try: if self.object_to_edit: action = EvalRow.EDIT else: action = EvalRow.CREATE row = EvalRow() row.anonymise_record(action=action, report=report, decrypted_text=report_text) row.save() except Exception as e: #TODO: real logging bugsnag.notify(e) pass #TODO: check if valid? return self.wizard_complete(report, **kwargs)
def clean_key(self): key = self.cleaned_data.get('key') report = self.report try: decrypted_report = report.decrypted_report(key) self.decrypted_report = decrypted_report #save anonymous row if one wasn't saved on creation try: row = EvalRow() row.set_identifiers(report) if (EvalRow.objects.filter(record_identifier = row.record_identifier).count() == 0): row.action = EvalRow.FIRST row.add_report_data(decrypted_report) row.save() except Exception as e: #TODO: real logging bugsnag.notify(e) pass except CryptoError: self.decrypted_report = None raise forms.ValidationError( self.error_messages['wrong_key'], code='wrong_key', ) return key
def send_notify(): backtrace = None try: raise ScaryException('foo') except: backtrace = sys.exc_info()[2] bugsnag.notify((Exception, Exception("foo"), backtrace))
def severity(request): bugsnag.notify( Exception("Bugsnag Django demo says: Look at the circle on the right side. It's different"), severity='info') return HttpResponse( "Bugsnag Django demo says: On <a href=\"bugsnag.com\">bugsnag.com</a> " + "look at the circle on the right side. It's different")
def get(self): bugsnag.notify( Exception("Bugsnag Tornado demo says: Look at the circle on the right side. It's different"), severity='info') self.write( "Bugsnag Tornado demo says: On <a href=\"bugsnag.com\">bugsnag.com</a> " + "look at the circle on the right side. It's different")
def export_report(request, report_id): owner = request.user report = Report.objects.get(id=report_id) if owner == report.owner: if request.method == 'POST': form = SecretKeyForm(request.POST) form.report = report if form.is_valid(): #record viewing in anonymous evaluation data try: row = EvalRow() row.anonymise_record(action=EvalRow.VIEW, report=report) row.save() except Exception as e: #TODO: real logging bugsnag.notify(e) pass try: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="callisto_report.pdf"' pdf = generate_pdf_report(toname=None, user=owner, report=report, decrypted_report=form.decrypted_report, report_id=None) response.write(pdf) return response except Exception as e: bugsnag.notify(e) form.add_error(None, "There was an error exporting your report.") else: form = SecretKeyForm() form.report = report return render(request, 'decrypt_record_for_view.html', {'form': form}) else: return HttpResponseForbidden()
def test_notify_metadata_bool_value(self): bugsnag.notify(ScaryException('unexpected failover'), value=True, value2=False) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual(True, event['metaData']['custom']['value']) self.assertEqual(False, event['metaData']['custom']['value2'])
def test_notify_unicode_metadata(self): bins = (u('\x98\x00\x00\x00\t\x81\x19\x1b\x00\x00\x00\x00\xd4\x07\x00' '\x00\x00\x00\x00\x00R\x00\x00\x00\x00\x00\xff\xff\xff\xffe' '\x00\x00\x00\x02project\x00%\x00\x00\x00f65f051b-d762-5983' '-838b-a05aadc06a5\x00\x02uid\x00%\x00\x00\x001bab969f-7b30' '-459a-adee-917b9e028eed\x00\x00')) self_class = 'tests.test_notify.TestBugsnag' bugsnag.notify(Exception('free food'), meta_data={'payload': { 'project': u('∆πåß∂ƒ'), 'filename': u('DISPOSITIFS DE SÉCURITÉ.pdf'), u('♥♥i'): u('♥♥♥♥♥♥'), 'src_name': u('☻☻☻☻☻ RDC DISPOSITIFS DE SÉCURTÉ.pdf'), u('accénted'): u('☘☘☘éééé@me.com'), 'class': self.__class__, 'another_class': dict, 'self': self, 'var': bins }}) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual(u('∆πåß∂ƒ'), event['metaData']['payload']['project']) self.assertEqual(u('♥♥♥♥♥♥'), event['metaData']['payload'][u('♥♥i')]) self.assertEqual(u('DISPOSITIFS DE SÉCURITÉ.pdf'), event['metaData']['payload']['filename']) self.assertEqual(u('☻☻☻☻☻ RDC DISPOSITIFS DE SÉCURTÉ.pdf'), event['metaData']['payload']['src_name']) self.assertEqual(u('☘☘☘éééé@me.com'), event['metaData']['payload'][u('accénted')]) self.assertEqual('test_notify_unicode_metadata (%s)' % self_class, event['metaData']['payload']['self']) self.assertEqual(bins, event['metaData']['payload']['var']) self.assertEqual("<class 'tests.test_notify.TestBugsnag'>", event['metaData']['payload']['class'])
def process_text(self, text, media_item): lines = text.split("\n") # Determine in the first 10 lines if it is an actual motion header = motion = False for line in lines[0:20]: if line.lower().endswith("der staten-generaal"): header = True continue if "motie" in line.lower() or "amendement" in line.lower(): motion = True break if not header or not motion: bugsnag.notify("Invalid motion, stop processing: ", severity="info", meta_data={"text": text}) opening_offset = 1 opening_number = None for opening_number, line in enumerate(lines): if line.startswith("gehoord de beraadslaging"): opening_number += opening_offset break closing_offset = 0 closing_number = None for closing_number, line in enumerate(lines): if line.startswith("en gaat over tot de orde van de dag"): closing_number += closing_offset break try: motion_lines = lines[opening_number:closing_number] except IndexError: motion_lines = None # Make last if motion_lines[-1][-1] in string.punctuation: motion_lines[-1] = motion_lines[-1][:-1] motion_lines[-1] += "." # The request in the motion is marked bold in Markdown first_request = True for request_number, line in enumerate(motion_lines): if line.startswith("verzoekt de") or line.startswith( "spreekt uit"): motion_lines[request_number] = "**" + line if not first_request: motion_lines[request_number - 1] += "**" first_request = False if not first_request: motion_lines[-1] += "**" media_item.text = "\n".join(motion_lines)
def report_bugsnag_in_worker(current_process, error, processed_count, args, show_error_messagebox=True): traceback_info = traceback.format_exc() # 打印错误日志 logger.info( "work thread {} unhandled exception={} when processing {}th work\nargs={}\n{}" .format(current_process, error, processed_count, args, traceback_info)) # 弹出错误框 if show_error_messagebox: notify_error( logger, "工作线程{}在处理第{}个计算项的搜索搭配过程中出现了未处理的异常\n{}".format( current_process, processed_count, traceback_info)) # 上报bugsnag cpu_name, physical_cpu_cores, manufacturer = get_hardward_info() meta_data = { "worker_task_info": { "args": args, }, "stacktrace_brief": { "info": traceback_info, }, "config": config(), "settings": all_settings(), "app": { "releaseStage": RUN_ENV, "version": now_version, "release_time": ver_time, }, "device": { "uuid": uuid.getnode(), "node": platform.node(), "osName": platform.system(), "osVersion": platform.version(), "release": platform.release(), "architecture": platform.machine(), "processor": platform.processor(), "logical_cpu_num": multiprocessing.cpu_count(), "physical_cpu_num": physical_cpu_cores, "cpu_name": cpu_name, "manufacturer": manufacturer, "time": time.strftime("%Y-%m-%d %H:%M:%S"), "timezone": time.strftime("%z", time.gmtime()), }, } bugsnag.notify( exception=error, context="worker", meta_data=meta_data, user={ "id": platform.node(), "uuid": uuid.getnode(), }, )
def test_notify_invalid_values_tuple(self): bugsnag.notify((None, 2, "foo")) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] exception = event['exceptions'][0] self.assertEqual(1, len(self.server.received)) self.assertEqual('RuntimeError', exception['errorClass']) self.assertTrue(repr(2) in exception['message'])
def log_exception(e, context_msg=None): if context_msg: msg = '%s: %s' % (context_msg, e.message) else: msg = e.message bugsnag.notify(e, context=context_msg) logging.error(msg)
def contextdivide(x, y): try: return x/y except ZeroDivisionError as e: bugsnag.notify(ZeroDivisionError('Celery+Django App: ' + 'Check the context of the notification'), context = 'celery.tasks.contextdivide' )
def test_notify_severity_overridden(self): bugsnag.notify(ScaryException("unexpected failover"), severity="info") json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertFalse(event['unhandled']) self.assertEqual(event['severityReason'], {"type": "userSpecifiedSeverity"})
def test_notify_metadata_filter(self): bugsnag.configure(params_filters=['apple', 'grape']) bugsnag.notify(ScaryException('unexpected failover'), apple='four', cantaloupe='green') json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual('[FILTERED]', event['metaData']['custom']['apple']) self.assertEqual('green', event['metaData']['custom']['cantaloupe'])
def test_notify_proxy(self): bugsnag.configure(proxy_host=self.server.url) bugsnag.notify(ScaryException('unexpected failover')) self.assertEqual(len(self.server.received), 1) self.assertEqual(self.server.received[0]['method'], 'POST') self.assertEqual(self.server.received[0]['path'].strip('/'), self.server.url)
def severitydivide(x, y): try: return x/y except ZeroDivisionError as e: bugsnag.notify(ZeroDivisionError('Celery+Django App: ' + 'The severity symbol on the right has changed'), severity = 'info' )
def test_notify_before_notify_modifying_api_key(self): def callback(report): report.api_key = 'sandwich' bugsnag.before_notify(callback) bugsnag.notify(ScaryException('unexpected failover')) json_body = self.server.received[0]['json_body'] self.assertEqual('sandwich', json_body['apiKey'])
def severitydivide(x, y): try: return x / y except ZeroDivisionError as e: bugsnag.notify( ZeroDivisionError('Celery+Django App: ' + 'The severity symbol on the right has changed'), severity='info')
def handle(self, *args, **options): try: file = io.open('cardlist.txt', 'rt') errors = io.open('failed.txt', 'w') booster = None count = 0 fail_count = 0 for line in file: if line.strip() == '': continue if line.startswith('###'): booster_name = line.strip('# \n') print booster_name booster = Booster.objects.get(name=booster_name) continue count += 1 try: response = requests.get('http://yugiohprices.com/api/card_data/' + line.strip()) json = response.json() except Exception, e: bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text }) json = None card = Card(name=line.strip()) if json and json['status'] == 'success': card.description = json['data']['text'] if json['data']['card_type'] == 'monster': card.attack = json['data']['atk'] card.defense = json['data']['def'] card.attribute = json['data']['family'].lower() card.level = json['data']['level'] card.save() types = [] for t in json['data']['type'].split('/'): ct = CardType.objects.get(name=t.strip()) types.append(ct.id) card.card_types = types else: card.effect_type = ('{} {}'.format(json['data']['property'], json['data']['card_type'])).lower() else: errors.write(line) errors.flush() fail_count += 1 card.save() card.boosters = [ booster.id ] card.save() print '{} - {} ({})'.format(booster.name, line.strip(), str(count)) except Exception, e: bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text })
def get(self): bugsnag.notify( Exception("Bugsnag Tornado demo says: False alarm, your application didn't crash"), Diagnostics={ "code": 200, "message": "Tornado demo says: Everything is great" }, User={ "email": "*****@*****.**", "username": "******" }) self.write( "Bugsnag Tornado demo says: It didn't crash! But still go check " + " <a href=\"bugsnag.com\">bugsnag.com</a> for a new notification. " + "Check out the User tab for the meta data")
def test_notify_unhandled_defaults(self): bugsnag.notify(ScaryException("unexpected failover")) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertFalse(event['unhandled']) self.assertEqual(event['severityReason'], { "type": "handledException" })
def test_notify_severity_overridden(self): bugsnag.notify(ScaryException("unexpected failover"), severity="info") json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertFalse(event['unhandled']) self.assertEqual(event['severityReason'], { "type": "userSpecifiedSeverity" })
def test_notify_recursive_metadata_dict(self): a = {'foo': 'bar'} a['baz'] = a bugsnag.add_metadata_tab('a', a) bugsnag.notify(ScaryException('unexpected failover')) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual('bar', event['metaData']['a']['foo']) self.assertEqual('[RECURSIVE]', event['metaData']['a']['baz']['baz'])
def test_notify_recursive_metadata_array(self): a = ['foo', 'bar'] a.append(a) bugsnag.add_metadata_tab('a', {'b': a}) bugsnag.notify(ScaryException('unexpected failover')) json_body = self.server.received[0]['json_body'] event = json_body['events'][0] self.assertEqual(['foo', 'bar', '[RECURSIVE]'], event['metaData']['a']['b'])
def notify_meta(request): bugsnag.notify( Exception("notify meta!"), Diagnostics={ "code": 200, "message": "Django demo says: Everything is great" }, User={"email": "*****@*****.**", "username": "******"}) return HttpResponse("notify meta!")
def test_notify_before_notify_modifying_api_key(self): def callback(report): report.api_key = 'sandwich' bugsnag.before_notify(callback) bugsnag.notify(ScaryException('unexpected failover')) headers = self.server.received[0]['headers'] self.assertEqual('sandwich', headers['Bugsnag-Api-Key'])