Skip to content

Commit

Permalink
improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
jperelli committed Sep 14, 2024
1 parent ffd0642 commit 6c2e552
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 3 additions & 1 deletion apps/core/middlewares/log.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.utils.deprecation import MiddlewareMixin
from django.core.exceptions import PermissionDenied

class BlockedBot(PermissionDenied):
pass

class LoggingMiddleware(MiddlewareMixin):
def process_request(self, request):
Expand All @@ -24,6 +26,6 @@ def process_request(self, request):
for blockua in blockuas:
if blockua in ua:
print('[BLOCK]', ip, ua, path)
raise PermissionDenied("Forbidden user agent")
raise BlockedBot("Blocked as Bot")

print('[-> OK]', ip, ua, path)
23 changes: 22 additions & 1 deletion config/settings/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@
INSTALLED_APPS = ['collectfast'] + INSTALLED_APPS # noqa F405
AWS_PRELOAD_METADATA = True

from ...apps.core.middlewares.log import BlockedBot
def skip_blocked_bot(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, BlockedBot):
return False
return True

# LOGGING
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
Expand All @@ -117,7 +125,20 @@
},
"root": {
"handlers": ["console"],
"level": "WARNING",
"level": "INFO",
},
'filters': {
'skip_blocked_bot': {
'()': 'django.utils.log.CallbackFilter',
'callback': skip_blocked_bot,
},
},
"loggers": {
"django.request": {
"level": "INFO",
'propagate': False,
'filters': ['skip_blocked_bot'],
},
},
}

Expand Down

0 comments on commit 6c2e552

Please sign in to comment.