66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
import json
|
|
import logging
|
|
import re
|
|
|
|
import structlog
|
|
from django.conf import settings
|
|
from rest_framework.throttling import UserRateThrottle
|
|
from structlog.types import EventDict
|
|
|
|
|
|
def structlog_add_app_info(
|
|
_: logging.Logger, __: str, event_dict: EventDict
|
|
) -> EventDict:
|
|
event_dict["django_app"] = "vbv_lernwelt"
|
|
event_dict["app_environment"] = settings.APP_ENVIRONMENT
|
|
event_dict["django_app_dev_mode"] = f"vbv_lernwelt_{settings.APP_ENVIRONMENT}"
|
|
|
|
return event_dict
|
|
|
|
|
|
def structlog_add_to_message(_: logging.Logger, __: str, event_dict: EventDict) -> str:
|
|
"""
|
|
The *event_dict* is added as dict ``message``.
|
|
|
|
This allows you to defer formatting to `logging`.
|
|
"""
|
|
return json.dumps(event_dict)
|
|
|
|
|
|
def structlog_inject_context_dict(test, level, event_dict):
|
|
"""
|
|
Add the structlog context dict to log events generated by the stdlib logging library.
|
|
"""
|
|
context_class = structlog.get_config().get("context_class")
|
|
|
|
if context_class:
|
|
for key, value in context_class().items():
|
|
if key not in event_dict:
|
|
event_dict[key] = value
|
|
|
|
return event_dict
|
|
|
|
|
|
class HourUserRateThrottle(UserRateThrottle):
|
|
scope = "hour-throttle"
|
|
|
|
|
|
class DayUserRateThrottle(UserRateThrottle):
|
|
scope = "day-throttle"
|
|
|
|
|
|
def find_first(iterable, pred=None, default=None):
|
|
return next(filter(pred, iterable), default)
|
|
|
|
|
|
def find_first_index(iterable, pred, default=None):
|
|
return next((i for i, x in enumerate(iterable) if pred(x)), default)
|
|
|
|
|
|
def replace_whitespace(text, replacement=" "):
|
|
return re.sub(r"\s+", replacement, text).strip()
|
|
|
|
|
|
def get_django_content_type(obj):
|
|
return obj._meta.app_label + "." + type(obj).__name__
|