Skip to content

Provide information about which specific rate limits were counted #322

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
7 changes: 6 additions & 1 deletion django_ratelimit/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
from django_ratelimit import ALL, UNSAFE
from django_ratelimit.exceptions import Ratelimited
from django_ratelimit.core import is_ratelimited
from django_ratelimit.logger import RatelimitLogger


__all__ = ['ratelimit']


def ratelimit(group=None, key=None, rate=None, method=ALL, block=True):
def ratelimit(group=None, key=None, rate=None, method=ALL, block=True,
logger: RatelimitLogger = None):
def decorator(fn):
@wraps(fn)
def _wrapped(request, *args, **kw):
Expand All @@ -20,6 +22,9 @@ def _wrapped(request, *args, **kw):
key=key, rate=rate, method=method,
increment=True)
request.limited = ratelimited or old_limited
if ratelimited and logger:
logger.log_ratelimit(request=request, group=group,
key=key, rate=rate, method=method)
if ratelimited and block:
cls = getattr(
settings, 'RATELIMIT_EXCEPTION_CLASS', Ratelimited)
Expand Down
19 changes: 19 additions & 0 deletions django_ratelimit/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import logging


class RatelimitLogger:

def __init__(self, name='', level=logging.WARNING,
msg_format="Ratelimit: {route} {group} \
{key} {rate} {method}"):
self.logger_name = name
self.msg_format = msg_format
self.level = level

def log_ratelimit(self, request, group, key, rate,
method) -> None:
logging.getLogger(self.logger_name).log(
level=self.level,
msg=self.msg_format
.format(route=request.resolver_match.route,
group=group, key=key, rate=rate, method=method))