Example #1
0
    def format(self, record: logging.LogRecord) -> str:
        from zerver.lib.request import get_current_request

        request = get_current_request()
        if not request:
            setattr(record, "user", None)
            setattr(record, "client", None)
            setattr(record, "url", None)
            setattr(record, "content_type", None)
            setattr(record, "custom_headers", None)
            setattr(record, "payload", None)
            return super().format(record)

        if request.content_type == "application/json":
            payload = request.body
        else:
            payload = request.POST.get("payload")

        try:
            payload = orjson.dumps(orjson.loads(payload),
                                   option=orjson.OPT_INDENT_2).decode()
        except orjson.JSONDecodeError:
            pass

        custom_header_template = "{header}: {value}\n"

        header_text = ""
        for header in request.META.keys():
            if header.lower().startswith("http_x"):
                header_text += custom_header_template.format(
                    header=header, value=request.META[header])

        header_message = header_text if header_text else None
        from zerver.lib.request import RequestNotes

        client = RequestNotes.get_notes(request).client
        assert client is not None

        setattr(
            record, "user",
            f"{request.user.delivery_email} ({request.user.realm.string_id})")
        setattr(record, "client", client.name)
        setattr(record, "url", request.META.get("PATH_INFO", None))
        setattr(record, "content_type", request.content_type)
        setattr(record, "custom_headers", header_message)
        setattr(record, "payload", payload)
        return super().format(record)
Example #2
0
    def format(self, record: logging.LogRecord) -> str:
        from zerver.lib.request import get_current_request
        request = get_current_request()
        if not request:
            setattr(record, 'user', None)
            setattr(record, 'client', None)
            setattr(record, 'url', None)
            setattr(record, 'content_type', None)
            setattr(record, 'custom_headers', None)
            setattr(record, 'payload', None)
            return super().format(record)

        if request.content_type == 'application/json':
            payload = request.body
        else:
            payload = request.POST.get('payload')

        try:
            payload = orjson.dumps(orjson.loads(payload),
                                   option=orjson.OPT_INDENT_2).decode()
        except orjson.JSONDecodeError:
            pass

        custom_header_template = "{header}: {value}\n"

        header_text = ""
        for header in request.META.keys():
            if header.lower().startswith('http_x'):
                header_text += custom_header_template.format(
                    header=header, value=request.META[header])

        header_message = header_text if header_text else None

        setattr(
            record, 'user',
            f"{request.user.delivery_email} (request.user.realm.string_id)")
        setattr(record, 'client', request.client.name)
        setattr(record, 'url', request.META.get('PATH_INFO', None))
        setattr(record, 'content_type', request.content_type)
        setattr(record, 'custom_headers', header_message)
        setattr(record, 'payload', payload)
        return super().format(record)
Example #3
0
def add_context(event: "Event", hint: "Hint") -> Optional["Event"]:
    if "exc_info" in hint:
        _, exc_value, _ = hint["exc_info"]
        # Ignore GeneratorExit, KeyboardInterrupt, and SystemExit exceptions
        if not isinstance(exc_value, Exception):
            return None
    from django.conf import settings

    from zerver.lib.request import RequestNotes, get_current_request
    from zerver.models import get_user_profile_by_id

    with capture_internal_exceptions():
        # event.user is the user context, from Sentry, which is
        # pre-populated with some keys via its Django integration:
        # https://docs.sentry.io/platforms/python/guides/django/enriching-error-data/additional-data/identify-user/
        event.setdefault("tags", {})
        user_info = event.get("user", {})
        if user_info.get("id"):
            user_profile = get_user_profile_by_id(user_info["id"])
            event["tags"]["realm"] = user_info[
                "realm"] = user_profile.realm.string_id or "root"
            with override_language(settings.LANGUAGE_CODE):
                # str() to force the lazy-translation to apply now,
                # since it won't serialize into json for Sentry otherwise
                user_info["role"] = str(user_profile.get_role_name())

        # These are PII, and should be scrubbed
        if "username" in user_info:
            del user_info["username"]
        if "email" in user_info:
            del user_info["email"]

        request = get_current_request()
        if request:
            request_notes = RequestNotes.get_notes(request)
            if request_notes.client is not None:
                event["tags"]["client"] = request_notes.client.name
            if request_notes.realm is not None:
                event["tags"].setdefault("realm",
                                         request_notes.realm.string_id)
    return event
Example #4
0
    def format(self, record: logging.LogRecord) -> str:
        from zerver.lib.request import get_current_request

        request = get_current_request()
        if not request:
            setattr(record, "user", None)
            setattr(record, "client", None)
            setattr(record, "url", None)
            setattr(record, "content_type", None)
            setattr(record, "custom_headers", None)
            setattr(record, "payload", None)
            return super().format(record)

        if request.content_type == "application/json":
            payload: Union[str, bytes] = request.body
        else:
            payload = request.POST["payload"]

        try:
            payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode()
        except orjson.JSONDecodeError:
            pass

        header_text = "".join(
            f"{header}: {value}\n"
            for header, value in request.headers.items()
            if header.lower().startswith("x-")
        )

        from zerver.lib.request import RequestNotes

        client = RequestNotes.get_notes(request).client
        assert client is not None

        setattr(record, "user", f"{request.user.delivery_email} ({request.user.realm.string_id})")
        setattr(record, "client", client.name)
        setattr(record, "url", request.META.get("PATH_INFO", None))
        setattr(record, "content_type", request.content_type)
        setattr(record, "custom_headers", header_text or None)
        setattr(record, "payload", payload)
        return super().format(record)