-
-
Save audiolion/debfb90f2a71255471e5ae0e3a8b87a5 to your computer and use it in GitHub Desktop.
Sentry Logger Event Hook for Python API Star 0.5+ (tested on 0.5.10)
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 sys | |
from os import environ | |
import logging | |
from apistar import http | |
from raven import Client | |
from apistar import App | |
from apistar.test import TestClient | |
from apistar import Route | |
settings = { | |
"SENTRY_PROJECT": "DNS", | |
"DEBUG": False | |
} # Or Django settings or whatever settings | |
_UNSAFE_ENV = ('SECRET', 'PASSWORD', 'PSSWRD') | |
sentry_client = Client(settings["SENTRY_PROJECT"]) | |
class SentryErrorHandlerHook: | |
@staticmethod | |
def sentry_error_handler( | |
req: http.Request, | |
query_params: http.QueryParams | |
): | |
def _get_safe_environ(): | |
safe_env = {} | |
for k, v in environ: | |
if k.upper() in _UNSAFE_ENV: | |
v = '*' * len(v) | |
safe_env[k] = v | |
return safe_env | |
if not getattr(settings, 'DEBUG', False): | |
data = { | |
'request': { | |
'url': req.url, | |
'method': req.method, | |
'query_string': dict(query_params), | |
'env': _get_safe_environ(), | |
'data': req.body.decode('utf-8'), | |
'headers': dict(req.headers), | |
} | |
} | |
exc_type, exc_value, exc_traceback = sys.exc_info() | |
message = f"{exc_type}{exc_value}{exc_traceback}" | |
ident = sentry_client.captureException(message=message, data=data) | |
return ident | |
def on_error( | |
self, | |
request: http.Request, | |
query_params: http.QueryParams, | |
): | |
""" | |
Logs unhandled exceptions | |
:return: | |
""" | |
ident = self.sentry_error_handler(request, query_params) or 'Unknown' | |
logging.fatal( | |
f'Error({ident}):' | |
f' Request ({request.method} {request.url})' | |
f' Headers ({dict(request.headers)})', | |
exc_info=True | |
) | |
def pitiful_get(): | |
raise Exception('This should never happens, but life is tough') | |
app = App( | |
routes=[Route('/shame'), name='shame', method="GET", handler=pitiful_get], | |
event_hooks=[SentryErrorHandlerHook] | |
) | |
test_client = TestClient(app=app) | |
# This will print a log an identifier of the error in Sentry, but it raises the Exception too | |
test_client.get('/shame') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment