How to use the ddtrace.constants.ANALYTICS_SAMPLE_RATE_KEY function in ddtrace

To help you get started, we’ve selected a few ddtrace examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DataDog / dd-trace-py / tests / contrib / mysqldb / test_mysql.py View on Github external
def test_analytics_without_rate(self):
        with self.override_config(
                'dbapi2',
                dict(analytics_enabled=True)
        ):
            conn, tracer = self._get_conn_tracer()
            writer = tracer.writer
            cursor = conn.cursor()
            cursor.execute('SELECT 1')
            rows = cursor.fetchall()
            assert len(rows) == 1
            spans = writer.pop()

            self.assertEqual(len(spans), 1)
            span = spans[0]
            self.assertEqual(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY), 1.0)
github DataDog / dd-trace-py / tests / contrib / psycopg / test_psycopg.py View on Github external
def test_analytics_default(self):
        conn = self._get_conn()
        conn.cursor().execute("""select 'blah'""")

        spans = self.get_spans()
        self.assertEqual(len(spans), 1)
        span = spans[0]
        self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
github DataDog / dd-trace-py / tests / contrib / django / test_middleware.py View on Github external
When making a request
            When an integration trace search is not event sample rate is not set and globally trace search is enabled
                We expect the root span to have the appropriate tag
        """
        with self.override_global_config(dict(analytics_enabled=True)):
            url = reverse('users-list')
            response = self.client.get(url)
            self.assertEqual(response.status_code, 200)

        spans = self.tracer.writer.pop()
        assert len(spans) == 3
        sp_request = spans[0]
        sp_template = spans[1]
        sp_database = spans[2]
        self.assertEqual(sp_request.name, 'django.request')
        self.assertEqual(sp_request.get_metric(ANALYTICS_SAMPLE_RATE_KEY), 1.0)
        self.assertIsNone(sp_template.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
        self.assertIsNone(sp_database.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
github DataDog / dd-trace-py / tests / contrib / flask / test_request.py View on Github external
We expect the root span to have the appropriate tag
        """
        @self.app.route('/')
        def index():
            return 'Hello Flask', 200

        with self.override_global_config(dict(analytics_enabled=True)):
            res = self.client.get('/')
            self.assertEqual(res.status_code, 200)
            self.assertEqual(res.data, b'Hello Flask')

        root = self.get_root_span()
        root.assert_matches(
            name='flask.request',
            metrics={
                ANALYTICS_SAMPLE_RATE_KEY: 1.0,
            },
        )

        for span in self.spans:
            if span == root:
                continue
            self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
github DataDog / dd-trace-py / tests / contrib / vertica / test_vertica.py View on Github external
def test_analytics_default(self):
        conn, cur = self.test_conn

        Pin.override(cur, tracer=self.test_tracer)

        with conn:
            cur.execute("INSERT INTO {} (a, b) VALUES (1, 'aa');".format(TEST_TABLE))
            cur.execute('SELECT * FROM {};'.format(TEST_TABLE))

        spans = self.test_tracer.writer.pop()
        self.assertEqual(len(spans), 2)
        self.assertIsNone(spans[0].get_metric(ANALYTICS_SAMPLE_RATE_KEY))
github DataDog / dd-trace-py / ddtrace / contrib / consul / patch.py View on Github external
def trace_func(wrapped, instance, args, kwargs):
        pin = Pin.get_from(instance)
        if not pin or not pin.enabled():
            return wrapped(*args, **kwargs)

        # Only patch the syncronous implementation
        if not isinstance(instance.agent.http, consul.std.HTTPClient):
            return wrapped(*args, **kwargs)

        path = kwargs.get('key') or args[0]
        resource = name.upper()

        with pin.tracer.trace(consulx.CMD, service=pin.service, resource=resource) as span:
            rate = config.consul.get_analytics_sample_rate()
            if rate is not None:
                span.set_tag(ANALYTICS_SAMPLE_RATE_KEY, rate)
            span.set_tag(consulx.KEY, path)
            span.set_tag(consulx.CMD, resource)
            return wrapped(*args, **kwargs)
github DataDog / dd-trace-py / ddtrace / contrib / requests / connection.py View on Github external
parsed_uri.params,
        None,  # drop parsed_uri.query
        parsed_uri.fragment
    ))

    with tracer.trace('requests.request', span_type=SpanTypes.HTTP) as span:
        # update the span service name before doing any action
        span.service = _extract_service_name(instance, span, hostname=hostname)

        # Configure trace search sample rate
        # DEV: analytics enabled on per-session basis
        cfg = config.get_from(instance)
        analytics_enabled = cfg.get('analytics_enabled')
        if analytics_enabled:
            span.set_tag(
                ANALYTICS_SAMPLE_RATE_KEY,
                cfg.get('analytics_sample_rate', True)
            )

        # propagate distributed tracing headers
        if cfg.get('distributed_tracing'):
            propagator = HTTPPropagator()
            propagator.inject(span.context, request.headers)

        # Storing request headers in the span
        store_request_headers(request.headers, span, config.requests)

        response = None
        try:
            response = func(*args, **kwargs)

            # Storing response headers in the span. Note that response.headers is not a dict, but an iterable
github DataDog / dd-trace-py / ddtrace / contrib / django / middleware.py View on Github external
tracer.context_provider.activate(context)
        try:
            span = tracer.trace(
                'django.request',
                service=settings.DEFAULT_SERVICE,
                resource='unknown',  # will be filled by process view
                span_type=http.TYPE,
            )

            # set analytics sample rate
            # DEV: django is special case maintains separate configuration from config api
            if (
                config.analytics_enabled and settings.ANALYTICS_ENABLED is not False
            ) or settings.ANALYTICS_ENABLED is True:
                span.set_tag(
                    ANALYTICS_SAMPLE_RATE_KEY,
                    settings.ANALYTICS_SAMPLE_RATE
                )

            span.set_tag(http.METHOD, request.method)

            # Do not fail if we cannot build an absoluate uri, use the request path as a fallback
            try:
                span.set_tag(http.URL, request.build_absolute_uri(request.path))
            except Exception:
                log.debug('failed to build absolute uri from %r', request.path, exc_info=True)
                span.set_tag(http.URL, request.path)

            _set_req_span(request, span)
        except Exception:
            log.debug('error tracing request', exc_info=True)
github DataDog / dd-trace-py / ddtrace / contrib / vertica / patch.py View on Github external
result = wrapped(*args, **kwargs)
                return result

            operation_name = conf['operation_name']
            tracer = pin.tracer
            with tracer.trace(operation_name, service=pin.service) as span:
                span.set_tags(pin.tags)
                if 'span_type' in conf:
                    span.span_type = conf['span_type']

                if 'span_start' in conf:
                    conf['span_start'](instance, span, conf, *args, **kwargs)

                # set analytics sample rate
                span.set_tag(
                    ANALYTICS_SAMPLE_RATE_KEY,
                    config.get_analytics_sample_rate()
                )

                result = wrapped(*args, **kwargs)
                return result
        except Exception as err:
            if 'on_error' in conf:
                conf['on_error'](instance, err, span, conf, *args, **kwargs)
            raise
        finally:
            # if an exception is raised result will not exist
            if 'result' not in locals():
                result = None
            if 'span_end' in conf:
                conf['span_end'](instance, result, span, conf, *args, **kwargs)
github DataDog / dd-trace-py / ddtrace / contrib / elasticsearch / patch.py View on Github external
params = kwargs.get('params')
            body = kwargs.get('body')

            span.service = pin.service
            span.set_tag(metadata.METHOD, method)
            span.set_tag(metadata.URL, url)
            span.set_tag(metadata.PARAMS, urlencode(params))
            if config.elasticsearch.trace_query_string:
                span.set_tag(http.QUERY_STRING, urlencode(params))
            if method == 'GET':
                span.set_tag(metadata.BODY, instance.serializer.dumps(body))
            status = None

            # set analytics sample rate
            span.set_tag(
                ANALYTICS_SAMPLE_RATE_KEY,
                config.elasticsearch.get_analytics_sample_rate()
            )

            span = quantize(span)

            try:
                result = func(*args, **kwargs)
            except elasticsearch.exceptions.TransportError as e:
                span.set_tag(http.STATUS_CODE, getattr(e, 'status_code', 500))
                raise

            try:
                # Optional metadata extraction with soft fail.
                if isinstance(result, tuple) and len(result) == 2:
                    # elasticsearch<2.4; it returns both the status and the body
                    status, data = result