From 3d08df84acc8c76f91c783bc932061bc60e64dbd Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Mon, 21 Aug 2017 10:01:23 +0200 Subject: [PATCH] Add a context manager to capture exceptions in sentry --- .../app/c2cwsgiutils_app/services.py | 6 ++++-- c2cwsgiutils/sentry.py | 16 ++++++++++++++++ setup.py | 2 +- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/acceptance_tests/app/c2cwsgiutils_app/services.py b/acceptance_tests/app/c2cwsgiutils_app/services.py index 4f3d81aac..b17b3a8b7 100644 --- a/acceptance_tests/app/c2cwsgiutils_app/services.py +++ b/acceptance_tests/app/c2cwsgiutils_app/services.py @@ -2,6 +2,7 @@ from pyramid.httpexceptions import HTTPForbidden from c2cwsgiutils import services +from c2cwsgiutils import sentry from c2cwsgiutils.stats import timer_context, increment_counter, set_gauge from c2cwsgiutils_app import models @@ -34,8 +35,9 @@ def hello_put(request): """ Will use the master """ - hello = models.DBSession.query(models.Hello).first() - return {'value': hello.value} + with sentry.capture_exceptions(): + hello = models.DBSession.query(models.Hello).first() + return {'value': hello.value} @hello_service.post() diff --git a/c2cwsgiutils/sentry.py b/c2cwsgiutils/sentry.py index fbf457f33..64cd81975 100644 --- a/c2cwsgiutils/sentry.py +++ b/c2cwsgiutils/sentry.py @@ -1,3 +1,4 @@ +import contextlib import logging import os from raven import Client @@ -5,9 +6,11 @@ from raven.conf import setup_logging LOG = logging.getLogger(__name__) +client = None def init(): + global client if 'SENTRY_URL' in os.environ: client_info = {key[14:].lower(): value for key, value in os.environ.items() if key.startswith('SENTRY_CLIENT_')} @@ -21,3 +24,16 @@ def init(): setup_logging(handler, exclude=('raven', )) LOG.info("Configured sentry reporting with client=%s", repr(client_info)) + + +@contextlib.contextmanager +def capture_exceptions(): + global client + if client is not None: + try: + yield + except: + client.captureException() + raise + else: + yield diff --git a/setup.py b/setup.py index 22a097fa6..acf7e3da8 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages -VERSION = '0.20.1' +VERSION = '0.21.0' HERE = os.path.abspath(os.path.dirname(__file__)) INSTALL_REQUIRES = open(os.path.join(HERE, 'requirements.txt')).read().splitlines()