Skip to content
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

chore(replay): add a log sampling filter and sample replay ingest logs #79879

Closed
wants to merge 5 commits into from
Closed
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
20 changes: 20 additions & 0 deletions src/sentry/logging/handlers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import random
import re

from django.utils.timezone import now
Expand Down Expand Up @@ -149,3 +150,22 @@ def emit(self, record, logger=None):
key = metrics_badchars_re.sub("", key)
key = ".".join(key.split(".")[:3])
metrics.incr(key, skip_internal=False)


class SamplingFilter(logging.Filter):
"""
A logging filter to sample messages at different rates.

prob_mapping -- a mapping of messages to probabilities. The msg must be an exact match.
Messages not in the mapping aren't filtered.
"""

def __init__(self, prob_mapping: dict[str, float]):
super().__init__()
self.prob_mapping = prob_mapping
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't abbreviate. probability_map or probability_mapping.


def filter(self, record: logging.LogRecord) -> bool:
msg = record.msg
if msg in self.prob_mapping:
return random.random() < self.prob_mapping[msg]
return True
14 changes: 13 additions & 1 deletion src/sentry/replays/consumers/recording_buffered.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,18 @@
from sentry_kafka_schemas.schema_types.ingest_replay_recordings_v1 import ReplayRecording

from sentry.conf.types.kafka_definition import Topic, get_topic_codec
from sentry.logging.handlers import SamplingFilter
from sentry.models.project import Project
from sentry.replays.lib.storage import (
RecordingSegmentStorageMeta,
make_recording_filename,
storage_kv,
)
from sentry.replays.usecases.ingest import process_headers, track_initial_segment_event
from sentry.replays.usecases.ingest import (
MOBILE_EVENT_SAMPLE_RATE,
process_headers,
track_initial_segment_event,
)
from sentry.replays.usecases.ingest.dom_index import (
ReplayActionsEvent,
emit_replay_actions,
Expand All @@ -72,6 +77,13 @@
from sentry.utils import json, metrics

logger = logging.getLogger(__name__)
logger.addFilter(
SamplingFilter(
{
"mobile_event": MOBILE_EVENT_SAMPLE_RATE,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this different from the other consumer?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you suggesting we add rrweb_event_count here too? It's not currently logged in this file

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No just asking the question. If we're not logging it we don't need to include it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're only logging mobile_event in this one

}
)
)

RECORDINGS_CODEC: Codec[ReplayRecording] = get_topic_codec(Topic.INGEST_REPLAYS_RECORDINGS)

Expand Down
12 changes: 12 additions & 0 deletions src/sentry/replays/usecases/ingest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from sentry_sdk.tracing import Span

from sentry.constants import DataCategory
from sentry.logging.handlers import SamplingFilter
from sentry.models.project import Project
from sentry.replays.lib.storage import (
RecordingSegmentStorageMeta,
Expand All @@ -24,7 +25,18 @@
from sentry.utils import json, metrics
from sentry.utils.outcomes import Outcome, track_outcome

MOBILE_EVENT_SAMPLE_RATE = 0.5
Copy link
Member Author

@aliu39 aliu39 Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sample rates defined here, can make them options if we want. Values right now are placeholders

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make this an option.

RRWEB_EVENT_COUNT_SAMPLE_RATE = 0.5

logger = logging.getLogger("sentry.replays")
logger.addFilter(
SamplingFilter(
{
"mobile_event": MOBILE_EVENT_SAMPLE_RATE,
"rrweb_event_count": RRWEB_EVENT_COUNT_SAMPLE_RATE,
Comment on lines +35 to +36
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are either of these log messages emitted in our consumer?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean a different file?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does "mobile_event" represent? The log message?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just realized I was looking at the event_type in extras. The msg is sentry.replays.slow_click. I'll have to rethink this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want different rates for these, or could we sample all slow click logs at the same rate for now?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same rate is fine.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you access the extra field within your sampler class?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can. The filter will become specific to our usecase though, so I'd move it into the init file

}
)
)

CACHE_TIMEOUT = 3600
COMMIT_FREQUENCY_SEC = 1
Expand Down
17 changes: 16 additions & 1 deletion tests/sentry/logging/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import pytest

from sentry.logging.handlers import JSONRenderer, StructLogHandler
from sentry.logging.handlers import JSONRenderer, SamplingFilter, StructLogHandler


@pytest.fixture
Expand Down Expand Up @@ -119,3 +119,18 @@ def test_logging_raiseExcpetions_enabled_generic_logging(caplog, snafu):
def test_logging_raiseExcpetions_disabled_generic_logging(caplog, snafu):
logger = logging.getLogger(__name__)
logger.log(logging.INFO, snafu)


@mock.patch("random.random", lambda: 0.5)
def test_sampling_filter(caplog):
logger = logging.getLogger(__name__)
logger.addFilter(SamplingFilter({"msg1": 0.8, "message.2": 0.3}))

logger.info("msg1")
logger.info("message.2")
logger.info("hello")

captured_msgs = list(map(lambda r: r.msg, caplog.records))
assert "msg1" in captured_msgs
assert "message.2" not in captured_msgs
assert "hello" in captured_msgs
Loading