Skip to content

Commit

Permalink
Merge branch 'master' into dependency_updates_2024_11
Browse files Browse the repository at this point in the history
  • Loading branch information
terjekv authored Nov 22, 2024
2 parents 172c363 + 64a7cd9 commit 6d70122
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
14 changes: 14 additions & 0 deletions hostpolicy/api/v1/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ def test_rename_to_name_in_use_400_bad_request(self):
self.assert_patch_and_400(self.basejoin(self.object_one.name),
{'name': self.object_two.name})

def test_filter_200_ok(self):
"""Filtering should return 200"""
response = self.assert_get(f"{self.basepath}?name={self.object_one.name}")
self.assertEqual(response.json()['count'], 1)
self.assertEqual(response.json()['results'][0]['name'], self.object_one.name)

response = self.assert_get(f"{self.basepath}?id={self.object_one.id}")
self.assertEqual(response.json()['count'], 1)
self.assertEqual(response.json()['results'][0]['name'], self.object_one.name)

class HostPolicyAtomTestCase(HostPolicyRoleTestCase):
"""This class defines the test suite for api/hostpolicyroles"""
Expand Down Expand Up @@ -127,6 +136,11 @@ def test_get_atoms_filtered_200_ok(self):
ret2 = self.assert_get('/api/v1/hostpolicy/atoms/?name__regex=.*testatom2.*')
self.assertEqual(ret2.json()['count'], 1)

ret2 = self.assert_get(f'/api/v1/hostpolicy/atoms/?id={self.object_two.id}')
self.assertEqual(ret2.json()['count'], 1)
self.assertEqual(ret2.json()['results'][0]['name'], self.object_two.name)



class HostPolicyAdminRights(MregAPITestCase):
"""Test that all of the API for HostPolicy are available for the admin group
Expand Down
2 changes: 2 additions & 0 deletions hostpolicy/api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class HostPolicyAtomFilterSet(filters.FilterSet):
class Meta:
model = HostPolicyAtom
fields = {
"id": INT_OPERATORS,
"name": STRING_OPERATORS,
"create_date": INT_OPERATORS,
"updated_at": INT_OPERATORS,
Expand All @@ -53,6 +54,7 @@ class HostPolicyRoleFilterSet(filters.FilterSet):
class Meta:
model = HostPolicyRole
fields = {
"id": INT_OPERATORS,
"name": STRING_OPERATORS,
"create_date": INT_OPERATORS,
"updated_at": INT_OPERATORS,
Expand Down
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)

0 comments on commit 6d70122

Please sign in to comment.