Skip to content

Instantly share code, notes, and snippets.

@adi-
Last active April 14, 2023 09:29
Show Gist options
  • Save adi-/1c5113c8ac2eaf4105cbc873e339d548 to your computer and use it in GitHub Desktop.
Save adi-/1c5113c8ac2eaf4105cbc873e339d548 to your computer and use it in GitHub Desktop.
Django middleware to send broken links to logger (vs standard send broken link by mail)
```
Django sends broken links by mail using built in middleware "BrokenLinkEmailsMiddleware".
This class alters that functionality and sends broken links to logger.
```
class BrokenLinkLogMiddleware(BrokenLinkEmailsMiddleware):
def process_response(self, request, response):
"""Log broken link for relevant 404 NOT FOUND responses."""
if response.status_code == 404 and not settings.DEBUG:
domain = request.get_host()
path = request.get_full_path()
referer = request.META.get("HTTP_REFERER", "")
if not self.is_ignorable_request(request, path, domain, referer):
ua = request.META.get("HTTP_USER_AGENT", "<none>")
ip = request.META.get("REMOTE_ADDR", "<none>")
logger.warning('Broken %slink on %s, Referrer: %s, Requested URL: %s, User agent: %s, IP address: %s'
% (
(
"INTERNAL "
if self.is_internal_request(domain, referer)
else ""
),
domain, referer, path, ua, ip
))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment