def hello_world():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("server_span"):
        return "Hello World!"
def create_trace_config(
    url_filter: _UrlFilterT = None,
    request_hook: _RequestHookT = None,
    response_hook: _ResponseHookT = None,
    tracer_provider: TracerProvider = None,
) -> aiohttp.TraceConfig:
    """Create an aiohttp-compatible trace configuration.

    One span is created for the entire HTTP request, including initial
    TCP/TLS setup if the connection doesn't exist.

    By default the span name is set to the HTTP request method.

    Example usage:

    .. code:: python

        import aiohttp
        from opentelemetry.instrumentation.aiohttp_client import create_trace_config

        async with aiohttp.ClientSession(trace_configs=[create_trace_config()]) as session:
            async with session.get(url) as response:
                await response.text()


    :param url_filter: A callback to process the requested URL prior to adding
        it as a span attribute. This can be useful to remove sensitive data
        such as API keys or user personal information.

    :param Callable request_hook: Optional callback that can modify span name and request params.
    :param Callable response_hook: Optional callback that can modify span name and response params.
    :param tracer_provider: optional TracerProvider from which to get a Tracer

    :return: An object suitable for use with :py:class:`aiohttp.ClientSession`.
    :rtype: :py:class:`aiohttp.TraceConfig`
    """
    # `aiohttp.TraceRequestStartParams` resolves to `aiohttp.tracing.TraceRequestStartParams`
    # which doesn't exist in the aiohttp intersphinx inventory.
    # Explicitly specify the type for the `request_hook` and `response_hook` param and rtype to work
    # around this issue.

    tracer = get_tracer(__name__, __version__, tracer_provider)

    def _end_trace(trace_config_ctx: types.SimpleNamespace):
        context_api.detach(trace_config_ctx.token)
        trace_config_ctx.span.end()

    async def on_request_start(
        unused_session: aiohttp.ClientSession,
        trace_config_ctx: types.SimpleNamespace,
        params: aiohttp.TraceRequestStartParams,
    ):
        if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
            trace_config_ctx.span = None
            return

        http_method = params.method.upper()
        request_span_name = "HTTP {}".format(http_method)

        trace_config_ctx.span = trace_config_ctx.tracer.start_span(
            request_span_name, kind=SpanKind.CLIENT,
        )

        if callable(request_hook):
            request_hook(trace_config_ctx.span, params)

        if trace_config_ctx.span.is_recording():
            attributes = {
                SpanAttributes.HTTP_METHOD: http_method,
                SpanAttributes.HTTP_URL: remove_url_credentials(
                    trace_config_ctx.url_filter(params.url)
                )
                if callable(trace_config_ctx.url_filter)
                else remove_url_credentials(str(params.url)),
            }
            for key, value in attributes.items():
                trace_config_ctx.span.set_attribute(key, value)

        trace_config_ctx.token = context_api.attach(
            trace.set_span_in_context(trace_config_ctx.span)
        )

        inject(params.headers)

    async def on_request_end(
        unused_session: aiohttp.ClientSession,
        trace_config_ctx: types.SimpleNamespace,
        params: aiohttp.TraceRequestEndParams,
    ):
        if trace_config_ctx.span is None:
            return

        if callable(response_hook):
            response_hook(trace_config_ctx.span, params)

        if trace_config_ctx.span.is_recording():
            trace_config_ctx.span.set_status(
                Status(http_status_to_status_code(int(params.response.status)))
            )
            trace_config_ctx.span.set_attribute(
                SpanAttributes.HTTP_STATUS_CODE, params.response.status
            )
        _end_trace(trace_config_ctx)

    async def on_request_exception(
        unused_session: aiohttp.ClientSession,
        trace_config_ctx: types.SimpleNamespace,
        params: aiohttp.TraceRequestExceptionParams,
    ):
        if trace_config_ctx.span is None:
            return

        if callable(response_hook):
            response_hook(trace_config_ctx.span, params)

        if trace_config_ctx.span.is_recording() and params.exception:
            trace_config_ctx.span.set_status(Status(StatusCode.ERROR))
            trace_config_ctx.span.record_exception(params.exception)
        _end_trace(trace_config_ctx)

    def _trace_config_ctx_factory(**kwargs):
        kwargs.setdefault("trace_request_ctx", {})
        return types.SimpleNamespace(
            tracer=tracer, url_filter=url_filter, **kwargs
        )

    trace_config = aiohttp.TraceConfig(
        trace_config_ctx_factory=_trace_config_ctx_factory
    )

    trace_config.on_request_start.append(on_request_start)
    trace_config.on_request_end.append(on_request_end)
    trace_config.on_request_exception.append(on_request_exception)

    return trace_config
Exemplo n.º 3
0
    def setUp(self):
        super().setUp()
        PymemcacheInstrumentor().instrument()

        # pylint: disable=protected-access
        self.tracer = get_tracer(__name__)
Exemplo n.º 4
0
def _get_tracer(engine, tracer_provider=None):
    return trace.get_tracer(
        _normalize_vendor(engine.name),
        __version__,
        tracer_provider=tracer_provider,
    )
Exemplo n.º 5
0
    def _instrumented_requests_call(
        method: str, url: str, call_wrapped, get_or_create_headers
    ):
        if context.get_value("suppress_instrumentation") or context.get_value(
            _SUPPRESS_REQUESTS_INSTRUMENTATION_KEY
        ):
            return call_wrapped()

        # See
        # https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-client
        method = method.upper()
        span_name = ""
        if name_callback is not None:
            span_name = name_callback(method, url)
        if not span_name or not isinstance(span_name, str):
            span_name = get_default_span_name(method)

        labels = {}
        labels["http.method"] = method
        labels["http.url"] = url

        with get_tracer(
            __name__, __version__, tracer_provider
        ).start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
            exception = None
            if span.is_recording():
                span.set_attribute("http.method", method)
                span.set_attribute("http.url", url)

            headers = get_or_create_headers()
            inject(headers)

            token = context.attach(
                context.set_value(_SUPPRESS_REQUESTS_INSTRUMENTATION_KEY, True)
            )
            try:
                result = call_wrapped()  # *** PROCEED
            except Exception as exc:  # pylint: disable=W0703
                exception = exc
                result = getattr(exc, "response", None)
            finally:
                context.detach(token)

            if isinstance(result, Response):
                if span.is_recording():
                    span.set_attribute("http.status_code", result.status_code)
                    span.set_attribute("http.status_text", result.reason)
                    span.set_status(
                        Status(http_status_to_status_code(result.status_code))
                    )
                labels["http.status_code"] = str(result.status_code)
                if result.raw and result.raw.version:
                    labels["http.flavor"] = (
                        str(result.raw.version)[:1]
                        + "."
                        + str(result.raw.version)[:-1]
                    )
            if span_callback is not None:
                span_callback(span, result)

            if exception is not None:
                raise exception.with_traceback(exception.__traceback__)

        return result
Exemplo n.º 6
0
 def get_app(self):
     tracer = trace.get_tracer(__name__)
     app = make_app(tracer)
     return app
Exemplo n.º 7
0
            # ConsoleSpanExporter(),
        )
    )

    # trace.get_tracer_provider().add_span_processor(
    #     SimpleExportSpanProcessor(
    #         ZipkinSpanExporter("rob-j", "http://host.docker.internal:9411/api/v2/spans", encoder=TransportFormat.V2_JSON),
    #         # ZipkinSpanExporter("rob", "http://host.docker.internal:9411/api/v2/spans", encoder=TransportFormat.V2_JSON),
    #         # OTLPSpanExporter(endpoint="host.docker.internal:55681", insecure=True, timeout=3),
    #         # ConsoleSpanExporter(),
    #     )
    # )

    provider = trace.get_tracer_provider()

    tracer = trace.get_tracer(__name__, "1.1r")

    with tracer.start_as_current_span("foo") as foo_span:
        foo_span.add_event("Alpha")
        foo_span.add_event("boom boom")
        foo_span.set_attribute("phone", "iphone X")
        foo_span.set_attribute("beats", "spotify")
        with tracer.start_as_current_span("bar") as bar_span:
            bar_span.add_event("Apocalypse")
            bar_span.set_attribute("sky", "blue")
            with tracer.start_as_current_span("baz") as baz_span:
                baz_span.add_event("event 1")
                baz_span.set_attribute('att1', 'att_val1')

    eadlwij = 1
    # sleep(500)
Exemplo n.º 8
0
def hello():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span('test_span'):
        return "SRE and DevOps work together!!! "
def span_call_child():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("step1") as span1:
        requests.get("http://jaeger-app-2-srv-2:5555/example6")
    return "simple call"
Exemplo n.º 10
0
 def __init__(self, wsgi, name_callback=get_default_span_name):
     self.wsgi = wsgi
     self.tracer = trace.get_tracer(__name__, __version__)
     self.name_callback = name_callback
 def __init__(self, wsgi, request_hook=None, response_hook=None):
     self.wsgi = wsgi
     self.tracer = trace.get_tracer(__name__, __version__)
     self.request_hook = request_hook
     self.response_hook = response_hook
Exemplo n.º 12
0
def hello():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("example-request"):
        requests.get("http://www.example.com")
    return "hello"
Exemplo n.º 13
0
 def test_get_tracer(self):
     """trace.get_tracer should proxy to the global tracer provider."""
     trace.get_tracer("foo", "var")
     self._mock_tracer_provider.get_tracer.assert_called_with("foo", "var")
Exemplo n.º 14
0
                              password=redis_password,
                              decode_responses=True)
        r.set("msg:hello", "Hello Redis!!!")
        msg = r.get("msg:hello")


#       print(msg)
    except Exception as e:
        print(e)

while True:

    hello_redis()  # redis is picked up by auto-instrumentation

    random_number = randint(0, 16777215)
    hex_number = str(hex(random_number))
    hex_number = hex_number[2:]
    printtime = datetime.datetime.now().strftime(
        "%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
    log_dict = {'transactionTime': printtime, 'transactionID': hex_number}

    tracer = trace.get_tracer(
        __name__)  # create a manual span for a logging operation called "log"
    with tracer.start_as_current_span("log", kind=SpanKind.SERVER) as span:
        span.set_attribute("transactionTime", printtime)
        span.set_attribute("transactionID", hex_number)
        print(json.dumps(log_dict))

    y = round(random(), 1) + .25
    sleep(y)
#   print('Sleeping: ', y)
Exemplo n.º 15
0
    def _instrumented_open_call(
        _, request, call_wrapped, get_or_create_headers
    ):  # pylint: disable=too-many-locals
        if context.get_value("suppress_instrumentation") or context.get_value(
            _SUPPRESS_HTTP_INSTRUMENTATION_KEY
        ):
            return call_wrapped()

        method = request.get_method().upper()
        url = request.full_url

        span_name = ""
        if name_callback is not None:
            span_name = name_callback(method, url)
        if not span_name or not isinstance(span_name, str):
            span_name = get_default_span_name(method)

        labels = {
            "http.method": method,
            "http.url": url,
        }

        with get_tracer(
            __name__, __version__, tracer_provider
        ).start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
            exception = None
            if span.is_recording():
                span.set_attribute("http.method", method)
                span.set_attribute("http.url", url)

            headers = get_or_create_headers()
            inject(headers)

            token = context.attach(
                context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True)
            )
            try:
                result = call_wrapped()  # *** PROCEED
            except Exception as exc:  # pylint: disable=W0703
                exception = exc
                result = getattr(exc, "file", None)
            finally:
                context.detach(token)

            if result is not None:

                code_ = result.getcode()
                labels["http.status_code"] = str(code_)

                if span.is_recording():
                    span.set_attribute("http.status_code", code_)
                    span.set_status(Status(http_status_to_status_code(code_)))

                ver_ = str(getattr(result, "version", ""))
                if ver_:
                    labels["http.flavor"] = "{}.{}".format(ver_[:1], ver_[:-1])

            if span_callback is not None:
                span_callback(span, result)

            if exception is not None:
                raise exception.with_traceback(exception.__traceback__)

        return result
def span_example8():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("step1") as span1:
        time.sleep(1)
        span_parallel_example8_process1()
    return "secuencial spans"
Exemplo n.º 17
0
def tracer():
    trace.set_tracer_provider(TracerProvider())
    return trace.get_tracer(__name__)
def span_parallel_example8_process1():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("process1") as span1:
        span_parallel_example7_process2()
Exemplo n.º 19
0
 def test_patch_applied_only_once(self):
     tracer = trace.get_tracer(__name__)
     self.assertTrue(patch_handler_class(tracer, AsyncHandler))
     self.assertFalse(patch_handler_class(tracer, AsyncHandler))
     self.assertFalse(patch_handler_class(tracer, AsyncHandler))
     unpatch_handler_class(AsyncHandler)
async def span_parallel_example9_process1():
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("process1") as span1:
        time.sleep(1)
        print("do something")
 def test_build(self):
     builder = SpanBuilder(get_tracer(__name__))
     builder.set_as_consumer()
     builder.set_destination('destination')
     span = builder.build()
     self.assertTrue(isinstance(span, Span))
 def setUp(self):
     super().setUp()
     LoggingInstrumentor().instrument()
     self.tracer = get_tracer(__name__)
Exemplo n.º 23
0
 def get_tracer(self):
     return get_tracer(
         self._name,
         instrumenting_library_version=self._version,
         tracer_provider=self._tracer_provider,
     )
Exemplo n.º 24
0
    def request(  # type:ignore
        self,
        method,
        url,
        query_params=None,
        headers=None,
        post_params=None,
        body=None,
        _preload_content=True,
        _request_timeout=None,
    ):
        headers = {} if headers is None else headers

        span_attributes = {
            "http.method": method,
            "http.url": url,
        }

        with get_tracer(__name__, __version__).start_as_current_span(
                f"External Api Call {self.__class__.__name__}",
                kind=SpanKind.CLIENT,
                attributes=span_attributes) as span:
            try:
                self.add_client_creds_token_header(headers)

                if self._tracing_enabled and not _is_instrumentation_suppressed(
                ):
                    inject(type(headers).__setitem__, headers)

                with _suppress_further_instrumentation():
                    response = super().request(  # type:ignore
                        method, url, query_params, headers, post_params, body,
                        _preload_content, _request_timeout)
                _apply_response(span, response)
                return response
            except Exception as ex:
                if is_api_exception(ex) and ex.status in (
                        HTTPStatus.UNAUTHORIZED,
                        HTTPStatus.FORBIDDEN):  # type:ignore
                    logger.warning("Access Denied. Token expired? Retrying.",
                                   api_exception=str(ex))
                    loop = new_event_loop()
                    loop.run_until_complete(
                        self.refresh_client_creds_token(force=True))
                    self.add_client_creds_token_header(headers)

                    if self._tracing_enabled and not _is_instrumentation_suppressed(
                    ):
                        inject(type(headers).__setitem__, headers)

                    with _suppress_further_instrumentation():
                        response = super().request(  # type:ignore
                            method, url, query_params, headers, post_params,
                            body, _preload_content, _request_timeout)
                    _apply_response(span, response)
                    return response

                else:
                    logger.exception("Could not call API.",
                                     client=self.__class__.__name__)
                    _apply_response(span, ex)
                    raise
Exemplo n.º 25
0
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from opentelemetry import trace

from splunk_otel import start_tracing

provider = start_tracing()

tracer = trace.get_tracer("simple", "0.1")


def main():
    with tracer.start_as_current_span(
        "custom span", kind=trace.SpanKind.INTERNAL
    ) as span:
        span.add_event("event1", {"k1": "v1"})


if __name__ == "__main__":
    main()
    provider.force_flush()
    provider.shutdown()
Exemplo n.º 26
0
 def __init__(self, wsgi):
     self.wsgi = wsgi
     self.tracer = trace.get_tracer(__name__, __version__)
Exemplo n.º 27
0
 def __init__(self, app, span_details_callback=None):
     self.app = guarantee_single_callable(app)
     self.tracer = trace.get_tracer(__name__, __version__)
     self.span_details_callback = (span_details_callback
                                   or get_default_span_details)
Exemplo n.º 28
0
 def get_current_tracer(cls):
     # type: () -> Tracer
     """
     Get the current tracer from the execution context. Return None otherwise.
     """
     return trace.get_tracer(__name__, __version__)
Exemplo n.º 29
0
    DatadogExportSpanProcessor(
        DatadogSpanExporter(agent_url="http://*****:*****@app.route("/server_request")
def server_request():
    param = request.args.get("param")
    with tracer.start_as_current_span("server-inner"):
        if param == "error":
            raise ValueError("forced server error")
        return "served: {}".format(param)


if __name__ == "__main__":
    app.run(port=8082)
Exemplo n.º 30
0
    def _instrumented_requests_call(method: str, url: str, call_wrapped,
                                    get_or_create_headers):
        if context.get_value("suppress_instrumentation") or context.get_value(
                _SUPPRESS_REQUESTS_INSTRUMENTATION_KEY):
            return call_wrapped()

        # See
        # https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md#http-client
        method = method.upper()
        span_name = "HTTP {}".format(method)

        recorder = RequestsInstrumentor().metric_recorder

        labels = {}
        labels["http.method"] = method
        labels["http.url"] = url

        with get_tracer(__name__, __version__,
                        tracer_provider).start_as_current_span(
                            span_name, kind=SpanKind.CLIENT) as span:
            exception = None
            with recorder.record_duration(labels):
                if span.is_recording():
                    span.set_attribute("component", "http")
                    span.set_attribute("http.method", method)
                    span.set_attribute("http.url", url)

                headers = get_or_create_headers()
                propagators.inject(type(headers).__setitem__, headers)

                token = context.attach(
                    context.set_value(_SUPPRESS_REQUESTS_INSTRUMENTATION_KEY,
                                      True))
                try:
                    result = call_wrapped()  # *** PROCEED
                except Exception as exc:  # pylint: disable=W0703
                    exception = exc
                    setattr(
                        exception,
                        EXCEPTION_STATUS_FIELD,
                        _exception_to_canonical_code(exception),
                    )
                    result = getattr(exc, "response", None)
                finally:
                    context.detach(token)

                if result is not None:
                    if span.is_recording():
                        span.set_attribute("http.status_code",
                                           result.status_code)
                        span.set_attribute("http.status_text", result.reason)
                        span.set_status(
                            Status(
                                http_status_to_canonical_code(
                                    result.status_code)))
                    labels["http.status_code"] = str(result.status_code)
                    labels["http.status_text"] = result.reason
                    if result.raw and result.raw.version:
                        labels["http.flavor"] = (str(result.raw.version)[:1] +
                                                 "." +
                                                 str(result.raw.version)[:-1])
                if span_callback is not None:
                    span_callback(span, result)

            if exception is not None:
                raise exception.with_traceback(exception.__traceback__)

        return result