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

Detailed logging of exceptions. #563

Merged
merged 3 commits into from
Nov 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion mreg/middleware/logging_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from typing import Callable, cast

import structlog
import sentry_sdk
import traceback
from django.conf import settings
from django.http import HttpRequest, HttpResponse

Expand Down Expand Up @@ -44,7 +46,13 @@ def __call__(self, request: HttpRequest) -> HttpResponse:
start_time = int(time.time())

self.log_request(request)
response = self.get_response(request)

try:
response = self.get_response(request)
except Exception as e:
self.log_exception(request, e, start_time)
raise

self.log_response(request, response, start_time)
return response

Expand Down Expand Up @@ -171,3 +179,44 @@ def log_response(
structlog.contextvars.clear_contextvars()

return response

def log_exception(self, request: HttpRequest, exception: Exception, start_time: float) -> None:
"""Log an exception that occurred during request processing."""
end_time = time.time()
run_time_ms = (end_time - start_time) * 1000

stack_trace = traceback.format_exc()

username = getattr(request.user, 'username', 'AnonymousUser')
user_agent = self._get_request_header(request, "user-agent", "HTTP_USER_AGENT")

# Log the exception with stack trace
mreg_logger.bind(
user=username,
method=request.method,
user_agent=user_agent,
path=request.path_info,
query_string=request.META.get("QUERY_STRING"),
run_time_ms=round(run_time_ms, 2),
).error(
"Unhandled exception occurred",
exception_string=str(exception),
exception_type=type(exception).__name__,
stack_trace=stack_trace,
)

# Capture the exception with Sentry and add context
with sentry_sdk.push_scope() as scope:
scope.set_user({"username": username})
scope.set_extra("method", request.method)
scope.set_extra("user_agent", user_agent)
scope.set_extra("path", request.path_info)
scope.set_extra("query_string", request.META.get("QUERY_STRING"))
scope.set_extra("run_time_ms", round(run_time_ms, 2))
scope.set_extra("exception_string", str(exception))
scope.set_extra("stack_trace", stack_trace)

scope.set_extra("request_body", self._get_body(request))

# Capture the exception
sentry_sdk.capture_exception(exception)