diff --git a/webvirtcloud/log_context.py b/webvirtcloud/log_context.py index df664d33..af431fdb 100644 --- a/webvirtcloud/log_context.py +++ b/webvirtcloud/log_context.py @@ -22,3 +22,11 @@ class RequestFilter(logging.Filter): except Exception: # the user may be read from the database here; a failure must not lose the line pass return True + + +class NotFoundFilter(logging.Filter): + """Leaves out django.request's line for a 404: scanners and old links + would bury the lines that matter.""" + + def filter(self, record): + return getattr(record, "status_code", None) != 404 diff --git a/webvirtcloud/settings.py.template b/webvirtcloud/settings.py.template index 994afac8..209ad568 100644 --- a/webvirtcloud/settings.py.template +++ b/webvirtcloud/settings.py.template @@ -256,6 +256,7 @@ LOGGING = { }, 'filters': { 'request': {'()': 'webvirtcloud.log_context.RequestFilter'}, + 'not_found': {'()': 'webvirtcloud.log_context.NotFoundFilter'}, }, 'handlers': { 'mail_admins': { @@ -282,6 +283,7 @@ LOGGING = { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, + "filters": ["not_found"], } }, } diff --git a/webvirtcloud/tests/test_logging.py b/webvirtcloud/tests/test_logging.py index 9e525408..153560a8 100644 --- a/webvirtcloud/tests/test_logging.py +++ b/webvirtcloud/tests/test_logging.py @@ -72,3 +72,14 @@ class RequestIdTestCase(TestCase): def test_an_id_sent_by_a_client_cannot_write_into_the_log(self): response = self.client.get("/accounts/login/", HTTP_X_REQUEST_ID="x\n[forged] line") self.assertRegex(response["X-Request-ID"], r"^[0-9a-f]{32}$") + + +class NotFoundTestCase(TestCase): + def test_a_404_is_not_logged_and_a_403_is(self): + self.client.force_login(User.objects.create_user("plain")) + with self.assertLogs("django.request", "WARNING") as logs: + self.client.get("/no-such-page/") + self.client.get("/admin/users/") + logging.getLogger("django.request").warning("end") # assertLogs needs one line + self.assertEqual([line.split(":")[0] for line in logs.output], ["WARNING", "WARNING"]) + self.assertIn("Forbidden", logs.output[0])