Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Record exceptions as 500 responses #27

Merged
merged 2 commits into from May 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions starlette_prometheus/middleware.py
Expand Up @@ -6,6 +6,7 @@
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Match
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
from starlette.types import ASGIApp

REQUESTS = Counter(
Expand Down Expand Up @@ -47,19 +48,21 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -

REQUESTS_IN_PROGRESS.labels(method=method, path_template=path_template).inc()
REQUESTS.labels(method=method, path_template=path_template).inc()
before_time = time.perf_counter()
try:
before_time = time.perf_counter()
response = await call_next(request)
after_time = time.perf_counter()
except Exception as e:
status_code = HTTP_500_INTERNAL_SERVER_ERROR
EXCEPTIONS.labels(method=method, path_template=path_template, exception_type=type(e).__name__).inc()
raise e from None
else:
status_code = response.status_code
after_time = time.perf_counter()
REQUESTS_PROCESSING_TIME.labels(method=method, path_template=path_template).observe(
after_time - before_time
)
RESPONSES.labels(method=method, path_template=path_template, status_code=response.status_code).inc()
finally:
RESPONSES.labels(method=method, path_template=path_template, status_code=status_code).inc()
REQUESTS_IN_PROGRESS.labels(method=method, path_template=path_template).dec()

return response
Expand Down
3 changes: 3 additions & 0 deletions tests/test_end_to_end.py
Expand Up @@ -67,6 +67,9 @@ def test_view_exception(self, client):
'exception_type="ValueError",method="GET",path_template="/bar/"'
"} 1.0" in metrics_text
)
assert (
"starlette_responses_total{" 'method="GET",path_template="/bar/",status_code="500"' "} 1.0" in metrics_text
)

# Asserts: Requests in progress
assert 'starlette_requests_in_progress{method="GET",path_template="/bar/"} 0.0' in metrics_text
Expand Down