Created
February 23, 2016 11:46
-
-
Save amol-/22be550c19853cfb21c5 to your computer and use it in GitHub Desktop.
OpBeat integration for TurboGears2
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
from tg.appwrappers.base import ApplicationWrapper | |
class OpBeatApplicationWrapper(ApplicationWrapper): | |
def __init__(self, handler, config): | |
super(OpBeatApplicationWrapper, self).__init__(handler, config) | |
from tg.support.converters import aslist | |
import logging | |
log = logging.getLogger('opbeat') | |
self.client = None | |
self.enabled = True | |
opbeat_app_id = config.get('opbeat.app_id') | |
if not opbeat_app_id: | |
self.enabled = False | |
if self.enabled: | |
opbeat_conf = dict( | |
name=config.get('opbeat.name'), | |
organization_id=config.get('opbeat.organization_id'), | |
app_id=opbeat_app_id, | |
secret_token=config.get('opbeat.secret_token'), | |
include_paths=aslist(config.get('opbeat.include_paths')), | |
exclude_paths=aslist(config.get('opbeat.exclude_paths')), | |
async_mode=True | |
) | |
import opbeat.instrumentation.control | |
from opbeat.base import Client | |
self.client = Client(**opbeat_conf) | |
opbeat.instrumentation.control.instrument() | |
log.debug('OpBeat enabled: %s -> %s', self.enabled, opbeat_conf) | |
@property | |
def injected(self): | |
return self.enabled | |
def __call__(self, controller, environ, context): | |
if self.client is None: | |
return self.next_handler(controller, environ, context) | |
controller_action = 'Unknown' | |
status_code = 500 | |
try: | |
self.client.begin_transaction("web.tg2") | |
resp = self.next_handler(controller, environ, context) | |
status_code = resp.status_code | |
dispatch_state = context.request.controller_state | |
controller_action = '{}.{}'.format(dispatch_state.controller.__class__.__name__, | |
dispatch_state.method.__name__) | |
return resp | |
except Exception: | |
request = context.request | |
extra = { | |
'url': request.url, | |
'user_agent': request.user_agent, | |
'client_ip_address': request.client_addr, | |
'status_code': 500 | |
} | |
error_data = { | |
'http': { | |
'url': request.url, | |
'method': request.method, | |
'query_string': request.query_string, | |
} | |
} | |
self.client.capture_exception(sys.exc_info(), extra=extra, data=error_data) | |
raise | |
finally: | |
self.client.end_transaction("web.tg2.{}".format(controller_action), status_code) | |
# ENABLE ADDING TO YOUR app_cfg.py FOLLOWING: | |
# from tg.appwrappers.transaction_manager import TransactionApplicationWrapper | |
# base_config.register_wrapper(OpBeatApplicationWrapper, after=TransactionApplicationWrapper) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment