Exemple #1
0
def main():
    sampler = always_on.AlwaysOnSampler()
    exporter = print_exporter.PrintExporter()
    #tracer = Tracer(sampler=sampler, exporter=exporter)
    je = JaegerExporter(service_name="pitoncito",
                        host_name='jaeger-server',
                        port=9411,
                        endpoint='/api/traces')
    tracer = Tracer(exporter=je, sampler=always_on.AlwaysOnSampler())

    with tracer.span(name='root'):
        tracer.add_attribute_to_current_span(attribute_key='miclave',
                                             attribute_value='mivalor')
        function_to_trace()
        with tracer.span(name='child'):
            function_to_trace()

    # Get the current tracer
    tracer = execution_context.get_opencensus_tracer()

    # Explicitly create spans
    tracer.start_span()

    # Get current span
    execution_context.get_current_span()

    # Explicitly end span
    tracer.end_span()
    def test_get_and_set_full_context(self):
        mock_tracer_get = mock.Mock()
        mock_span_get = mock.Mock()
        execution_context.set_opencensus_tracer(mock_tracer_get)
        execution_context.set_current_span(mock_span_get)

        execution_context.set_opencensus_attr("test", "test_value")

        tracer, span, attrs = execution_context.get_opencensus_full_context()

        self.assertEqual(mock_tracer_get, tracer)
        self.assertEqual(mock_span_get, span)
        self.assertEqual({"test": "test_value"}, attrs)

        mock_tracer_set = mock.Mock()
        mock_span_set = mock.Mock()

        execution_context.set_opencensus_full_context(mock_tracer_set,
                                                      mock_span_set, None)
        self.assertEqual(mock_tracer_set,
                         execution_context.get_opencensus_tracer())
        self.assertEqual(mock_span_set, execution_context.get_current_span())
        self.assertEqual({}, execution_context.get_opencensus_attrs())

        execution_context.set_opencensus_full_context(
            mock_tracer_set, mock_span_set, {"test": "test_value"})
        self.assertEqual("test_value",
                         execution_context.get_opencensus_attr("test"))
    def _teardown_request(self, exception):
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return

        try:
            tracer = execution_context.get_opencensus_tracer()

            if exception is not None:
                span = execution_context.get_current_span()
                span.status = status.Status(
                    code=code_pb2.UNKNOWN,
                    message=str(exception)
                )
                # try attaching the stack trace to the span, only populated if
                # the app has 'PROPAGATE_EXCEPTIONS', 'DEBUG', or 'TESTING'
                # enabled
                exc_type, _, exc_traceback = sys.exc_info()
                if exc_traceback is not None:
                    span.stack_trace = stack_trace.StackTrace.from_traceback(
                        exc_traceback
                    )

            tracer.end_span()
            tracer.finish()
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
Exemple #4
0
def _on_finish(func, handler, args, kwargs):
    if execution_context.get_opencensus_attr(TORNADO_EXCEPTION) is not None:
        return

    tracer = execution_context.get_opencensus_tracer()
    span = execution_context.get_current_span()
    span.add_attribute(attribute_key=HTTP_STATUS_CODE,
                       attribute_value=str(handler.get_status()))
    tracer.finish()
    return func(*args, **kwargs)
Exemple #5
0
    def test__end_span_between_context(self):
        from opencensus.trace import execution_context

        current_span = mock.Mock()
        tracer = mock.Mock()
        interceptor = client_interceptor.OpenCensusClientInterceptor(
            tracer=tracer, host_port='test')
        interceptor._end_span_between_context(current_span)

        span_in_context = execution_context.get_current_span()

        self.assertEqual(span_in_context, current_span)
        self.assertTrue(tracer.end_span.called)
    def test_clean_span(self):
        mock_span = mock.Mock()
        some_value = mock.Mock()
        execution_context.set_current_span(mock_span)

        thread_local = threading.local()
        setattr(thread_local, 'random_non_oc_attr', some_value)

        execution_context.clean()

        self.assertNotEqual(mock_span, execution_context.get_current_span())
        self.assertEqual(some_value, getattr(thread_local,
                                             'random_non_oc_attr'))
Exemple #7
0
def main():
    sampler = always_on.AlwaysOnSampler()
    exporter = print_exporter.PrintExporter()
    tracer = Tracer(sampler=sampler, exporter=exporter)

    with tracer.span(name='root'):
        tracer.add_attribute_to_current_span(attribute_key='example key',
                                             attribute_value='example value')
        function_to_trace()
        with tracer.span(name='child'):
            function_to_trace()

    # Get the current tracer
    tracer = execution_context.get_opencensus_tracer()

    # Explicitly create spans
    tracer.start_span()

    # Get current span
    execution_context.get_current_span()

    # Explicitly end span
    tracer.end_span()
Exemple #8
0
def _log_exception(func, handler, args, kwargs):
    value = args[1] if len(args) == 3 else None
    if value is None:
        return func(*args, **kwargs)

    tracer = execution_context.get_opencensus_tracer()
    if not isinstance(value, HTTPError) or 500 <= value.status_code <= 599:
        span = execution_context.get_current_span()
        span.add_attribute(attribute_key=HTTP_STATUS_CODE,
                           attribute_value=str(handler.get_status()))
        tracer.finish()

        execution_context.set_opencensus_attr(TORNADO_EXCEPTION, True)

    return func(*args, **kwargs)
Exemple #9
0
    def test_end_span_without_parent(self, mock_current_span):
        from opencensus.trace.execution_context import get_current_span

        tracer = context_tracer.ContextTracer()
        mock_span = mock.Mock()
        mock_span.name = 'span'
        mock_span.children = []
        mock_span.status = None
        mock_span.links = None
        mock_span.stack_trace = None
        mock_span.time_events = None
        mock_span.attributes = {}
        mock_span.__iter__ = mock.Mock(return_value=iter([mock_span]))
        mock_current_span.return_value = mock_span
        tracer.end_span()

        cur_span = get_current_span()
        self.assertIsNone(cur_span)
Exemple #10
0
 def process_log_record(self, log_record):
     # Set some parameters from
     # https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
     # and https://cloud.google.com/logging/docs/agent/configuration
     log_record['severity'] = log_record['levelname']
     del log_record['levelname']
     tracer = execution_context.get_opencensus_tracer()
     trace_id = tracer.span_context.trace_id
     log_record[
         'logging.googleapis.com/trace'] = "projects/{0}/traces/{1}".format(  # noqa
             settings.STACKDRIVER_TRACE_PROJECT_ID, trace_id)
     if not isinstance(tracer, NoopTracer):
         current_span = execution_context.get_current_span()
         span_id = current_span.span_id if current_span else None
     else:
         span_id = None
     log_record['logging.googleapis.com/spanId'] = span_id
     return super(StackdriverJsonFormatter,
                  self).process_log_record(log_record)
Exemple #11
0
    def current_span(self):
        """Return the current span."""
        current_span = execution_context.get_current_span()

        return current_span
Exemple #12
0
 def get_current_span(cls):
     # type: () -> Span
     """
     Get the current span from the execution context. Return None otherwise.
     """
     return execution_context.get_current_span()
def get_current_span():
    return execution_context.get_current_span()
 def get(self):
     span = ec.get_current_span()
     assert span is not None
     yield self.do_something(span)
     assert ec.get_current_span() is span
     self.write('{}')
Exemple #15
0
 def get(self):
     span = ec.get_current_span()
     assert span is None
 def verify_request(self, request):
     if self.assert_current_span:
         assert execution_context.get_current_span() is not None
     return self.expected_response
Exemple #17
0
def _trace(func, *args, **kwargs):
    with get_current_span().span(name=func.__name__):
        return func(*args, **kwargs)