Last active
January 27, 2016 18:49
-
-
Save mikeckennedy/618f4157a6268ddab8fd to your computer and use it in GitHub Desktop.
Add opbeat integration to Pyramid web apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import opbeat | |
import opbeat.instrumentation | |
import opbeat.instrumentation.control | |
from pyramid.events import NewRequest | |
from pyramid.events import subscriber | |
from pyramid.httpexceptions import HTTPRedirection, HTTPException | |
opbeat_is_debug_mode = False | |
opbeat.instrumentation.control.instrument() | |
# todo: update with your details | |
opbeat_client = opbeat.Client( | |
organization_id=opbeat_credentials.organization_id, | |
app_id=opbeat_credentials.app_id, | |
secret_token=opbeat_credentials.secret_token, | |
async_mode=True, | |
) | |
@subscriber(NewRequest) | |
def __opbeat_new_request_callback(event): | |
global opbeat_client | |
if not opbeat_is_debug_mode: | |
opbeat_client.begin_transaction("web.pyramid") | |
event.request.add_finished_callback(lambda r: __opbeat_request_done_callback(r, opbeat_client)) | |
def __opbeat_request_done_callback(request, client): | |
route_name = '__unknown_activity__' | |
status_code = request.response.status_code | |
try: | |
if request.matched_route and request.matched_route.name: | |
route_name = request.matched_route.name | |
if request.exc_info: | |
status_code = __record_exception_at_opbeat(client, request) | |
finally: | |
if not opbeat_is_debug_mode: | |
client.end_transaction("web.pyramid.{}".format(route_name), status_code) | |
def __record_exception_at_opbeat(client, request): | |
if not request.exc_info: | |
return 500 | |
ex_value = request.exc_info[1] | |
is_redirect_exception = ex_value and isinstance(ex_value, HTTPRedirection) | |
if is_redirect_exception: | |
return ex_value.code | |
status_code = 500 | |
if isinstance(ex_value, HTTPException): | |
status_code = ex_value.code | |
extra = { | |
'url': request.url, | |
'user_agent': request.user_agent, | |
'client_ip_address': request.client_addr, | |
'status_code': status_code | |
} | |
error_data = { | |
'http': { | |
'url': request.url, | |
'method': request.method, | |
'query_string': request.query_string, | |
}, | |
'site': opbeat_credentials.site_name, | |
} | |
if not opbeat_is_debug_mode: | |
client.capture_exception(request.exc_info, extra=extra, data=error_data) | |
return status_code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment