Example #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()
Example #2
0
def process(auth_context, form):
    """
    View function for processing charges.

    Parameters:
       auth_context (dict): The authentication context of request.
                            See middlewares/auth.py for more information.
       form (CheckOutForm): A validated checkout form.
                            See middlewares/form_validation.py for more
                            information.
    Output:
       Rendered HTML page.
    """

    # Create an OpenCensus tracer to trace each payment process, and export
    # the data to Stackdriver Tracing.
    tracer = Tracer(exporter=sde)
    trace_id = tracer.span_context.trace_id

    # Prepare the order
    with tracer.span(name="prepare_order_info"):
        product_ids = form.product_ids.data
        stripe_token = form.stripeToken.data
        shipping = orders.Shipping(address_1=form.address_1.data,
                                   address_2=form.address_2.data,
                                   city=form.city.data,
                                   state=form.state.data,
                                   zip_code=form.zip_code.data,
                                   email=form.email.data,
                                   mobile=form.mobile.data)
        amount = product_catalog.calculate_total_price(product_ids)
        order = orders.Order(amount=amount,
                             shipping=shipping,
                             status="order_created",
                             items=product_ids)
        order_id = orders.add_order(order)

    # Stream a Payment event
    with tracer.span(name="send_payment_event"):
        if stripe_token:
            # Publish an event to the topic for new payments.
            # Cloud Function pay_with_stripe subscribes to the topic and
            # processes the payment using the Stripe API upon arrival of new
            # events.
            # Cloud Function streamEvents (or App Engine service stream-event)
            # subscribes to the topic and saves the event to BigQuery for
            # data analytics upon arrival of new events.
            eventing.stream_event(
                topic_name=PUBSUB_TOPIC_PAYMENT_PROCESS,
                event_type='order_created',
                event_context={
                    'order_id': order_id,
                    'token': stripe_token,
                    # Pass the trace ID in the event so that Cloud Function
                    # pay_with_stripe can continue the trace.
                    'trace_id': trace_id
                })

    return render_template("charge.html", auth_context=auth_context)
Example #3
0
async def middlewareOpencensus(
    request: Request, call_next
):  # The middleware function recieves: The request, A function call_next that will recieve the request as a parameter
    tracer = Tracer(exporter=AzureExporter(
        connection_string=f'InstrumentationKey={APPINSIGHTS_INSTRUMENTATIONKEY}'
    ),
                    sampler=ProbabilitySampler(1.0))
    # https://opencensus.io/tracing/span/kind/#2
    # SpanKind details the relationships between spans in addition to the parent/child relationship.
    # Spand kind: 0 = UNSEPCIFIED, 1 = SERVER, 2 = CLIENT
    # Detail explaination of Span : https://opencensus.io/tracing/span/
    with tracer.span("main") as span:
        span.span_kind = SpanKind.SERVER

        response = await call_next(
            request
        )  # call next will pass the request to the corresponding path operation, then returns the response genrated by the corresponding path operation

        tracer.add_attribute_to_current_span(  # current span is a SERVER
            attribute_key=HTTP_STATUS_CODE,  # E.g. 202, 201, 404, 405, 505
            attribute_value=response.status_code)
        tracer.add_attribute_to_current_span(attribute_key=HTTP_URL,
                                             attribute_value=str(request.url))

    return response
Example #4
0
def sleep(request: InvokeMethodRequest) -> InvokeMethodResponse:
    tracer = Tracer(sampler=AlwaysOnSampler())
    with tracer.span(name='sleep') as _:
        time.sleep(2)
        print(request.metadata, flush=True)
        print(request.text(), flush=True)

        return InvokeMethodResponse(b'SLEEP', "text/plain; charset=UTF-8")
Example #5
0
def say(request: InvokeMethodRequest) -> InvokeMethodResponse:
    tracer = Tracer(sampler=AlwaysOnSampler())
    with tracer.span(name='say') as span:
        data = request.text()
        span.add_annotation('Request length', len=len(data))
        print(request.metadata, flush=True)
        print(request.text(), flush=True)

        return InvokeMethodResponse(b'SAY', "text/plain; charset=UTF-8")
Example #6
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()
Example #7
0
def create_order(product_ids, stripe_token, shipping):
    # Create an OpenCensus tracer to trace each payment process, and export
    # the data to Stackdriver Tracing.
    tracer = Tracer(exporter=sde)
    trace_id = tracer.span_context.trace_id

    # Prepare the order
    with tracer.span(name="prepare_order_info"):
        amount = product_catalog.calculate_total_price(product_ids)
        order = orders.Order(amount=amount,
                             shipping=shipping,
                             status="order_created",
                             items=product_ids)
        order_id = orders.add_order(order)

    # Stream a Payment event
    with tracer.span(name="send_payment_event"):
        if stripe_token:
            # Publish an event to the topic for new payments.
            # Cloud Function pay_with_stripe subscribes to the topic and
            # processes the payment using the Stripe API upon arrival of new
            # events.
            # Cloud Function streamEvents (or App Engine service stream-event)
            # subscribes to the topic and saves the event to BigQuery for
            # data analytics upon arrival of new events.
            eventing.stream_event(
                topic_name=PUBSUB_TOPIC_PAYMENT_PROCESS,
                event_type='order_created',
                event_context={
                    'order_id': order_id,
                    'token': stripe_token,
                    # Pass the trace ID in the event so that Cloud Function
                    # pay_with_stripe can continue the trace.
                    'trace_id': trace_id,
                    'email': shipping.email
                }
            )
Example #8
0
    async def dispatch(self, request: Request, call_next):
        propagator = TraceContextPropagator()
        span_context = propagator.from_headers(dict(request.headers))

        tracer = Tracer(exporter=self.exporter,
                        sampler=self.sampler,
                        span_context=span_context,
                        propagator=propagator)

        try:
            # tracer.span_context.trace_options.set_enabled(True)

            with tracer.span(f"[{request.method}] {request.url}") as span:
                span.span_kind = SpanKind.SERVER
                # if "traceparent" not in request.headers:
                #     trace_ctx = span.context_tracer
                #     trace_options = tracer.span_context.trace_options.trace_options_byte
                #     trace_id = trace_ctx.trace_id
                #     trace_parent = f"00-{trace_id}-{span.span_id}-0{trace_options}"
                # else:
                #     trace_parent = request.headers['traceparent']

                span.add_attribute(HTTP_URL, str(request.url))
                span.add_attribute(HTTP_HOST, request.url.hostname)
                span.add_attribute(HTTP_METHOD, request.method)
                span.add_attribute(HTTP_PATH, request.url.path)
                span.add_attribute(HTTP_ROUTE, request.url.path)
                span.add_attribute("x_forwarded_host",
                                   request.headers.get("x_forwarded_host"))

                for key, value in self.extra_attrs.items():
                    span.add_attribute(key, value)

                response = await call_next(request)
                # response.headers['traceparent'] = trace_parent

                span.add_attribute(HTTP_STATUS_CODE, response.status_code)

            return response

        except Exception as err:
            logger.error(err, exc_info=True)
        finally:
            tracer.finish()
    def Echo(self, request, context):
        metadata = context.invocation_metadata()
        logging.debug("Echo metadata: " + str(metadata))
        metadata_dict = GetTracingMetadata(context)
        logging.debug("Metadata dict: " + str(metadata_dict))

        if 'x-b3-traceid' in metadata_dict:
            trace_id = metadata_dict['x-b3-traceid']
            logging.debug("Trace ID: " + trace_id)
            span_context = SpanContext(trace_id=trace_id,
                                       span_id=metadata_dict['x-b3-spanid'])
            tracer = Tracer(span_context=span_context,
                            exporter=exporter,
                            sampler=always_on.AlwaysOnSampler())
            with tracer.span(name='echo') as span:
                logging.debug("Processing Echo: " + str(request))
                span.add_attribute("message", request.message)
                time.sleep(0.2)
        return echo_pb2.EchoResponse(message=request.message)
Example #10
0
def pay_with_stripe(data, context):
    tracer = Tracer(exporter=sde)

    if 'data' in data:
        payment_request_json = base64.b64decode(data.get('data')).decode()
        payment_request = json.loads(payment_request_json)
        token = payment_request.get('event_context').get('token')
        order_id = payment_request.get('event_context').get('order_id')
        trace_id = payment_request.get('event_context').get('trace_id')
        tracer.span_context.trace_id = trace_id

        with tracer.span(name="process_payment"):
            order_data = firestore.collection('orders').document(
                order_id).get().to_dict()
            amount = order_data.get('amount')
            email = order_data.get('shipping').get('email')

            try:
                charge = stripe.Charge.create(
                    # For US Dollars, Stripe use Cent as the unit
                    amount=int(amount * 100),
                    currency='usd',
                    description='Example charge',
                    source=token)
                order_data['status'] = 'payment_processed'
                event_type = 'payment_processed'

            except stripe.error.StripeError as err:
                print(err)
                order_data['status'] = 'payment_failed'
                event_type = 'payment_failed'

            firestore.collection('orders').document(order_id).set(order_data)
            stream_event(topic_name=PUBSUB_TOPIC_PAYMENT_COMPLETION,
                         event_type=event_type,
                         event_context={
                             'order_id': order_id,
                             'email': email,
                             'order': order_data
                         })

    return ''
def test_get_span_from_thread():

    result = []
    def get_span_from_thread(output):
        current_span = OpenCensusSpan.get_current_span()
        output.append(current_span)

    tracer = Tracer(sampler=AlwaysOnSampler())
    with tracer.span(name="TestSpan") as span:

        thread = threading.Thread(
            target=get_span_from_thread,
            args=(result,)
        )
        thread.start()
        thread.join()

        assert span is result[0]

    execution_context.clear()
    def test_invoke_method_with_tracer(self):
        tracer = Tracer(sampler=samplers.AlwaysOnSampler(),
                        exporter=print_exporter.PrintExporter())

        self.client = DaprClient(headers_callback=lambda: tracer.propagator.
                                 to_headers(tracer.span_context))
        self.server.set_response(b"FOO")

        with tracer.span(name="test"):
            req = common_v1.StateItem(key='test')
            resp = self.client.invoke_method(
                self.app_id,
                self.method_name,
                http_verb='PUT',
                data=req,
            )

        request_headers = self.server.get_request_headers()

        self.assertIn('Traceparent', request_headers)
        self.assertEqual(b'FOO', resp.data)
Example #13
0
    async def dispatch(self, request: Request, call_next):
        if (request.app.extra.get('extra', {}).get('open-census-settings',
                                                   {})):
            settings = request.app.extra['extra']['open-census-settings']
            self.load_config(settings=settings)

        if hasattr(request.app, 'trace_exporter'):
            self.exporter = request.app.trace_exporter

        span_context = self.propagator.from_headers(request.headers)
        tracer = Tracer(span_context=span_context,
                        sampler=self.sampler,
                        propagator=self.propagator,
                        exporter=self.exporter)
        with tracer.span("main") as span:
            span.span_kind = SpanKind.SERVER

            self._before_request(request, tracer)
            response = await call_next(request)
            self._after_request(response, tracer)

        return response
def create_trace_dependency(name=name,
                            message=message,
                            message_before=message_before,
                            message_after=message_after):
    config_integration.trace_integrations(['logging'])

    logger = logging.getLogger(__name__)

    handler = AzureLogHandler(connection_string='InstrumentationKey=%s' %
                              (instrument_key))
    handler.setFormatter(
        logging.Formatter('%(traceId)s %(spanId)s %(message)s'))
    logger.addHandler(handler)

    tracer = Tracer(exporter=AzureExporter(
        connection_string='InstrumentationKey=%s' % (instrument_key)),
                    sampler=ProbabilitySampler(1.0))

    logger.warning(message_before)
    with tracer.span(name=name):
        logger.warning(message)
    logger.warning(message_after)
Example #15
0
from opencensus.trace.samplers import always_on, always_off
from opencensus.trace.tracer import Tracer

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


def is_enabled():
    return getattr(settings, 'TRACING_ENABLED', False)


# Setup the exporter
ze = zipkin.ZipkinExporter(service_name=getattr(settings, 'TRACING_SERVICE',
                                                'snoop'),
                           host_name=getattr(settings, 'TRACING_HOST',
                                             'zipkin'),
                           port=getattr(settings, 'TRACING_PORT', 9411),
                           endpoint=getattr(settings, 'TRACING_API',
                                            '/api/v2/spans'))

# If enabled configure 100% sample rate, otherwise, 0% sample rate
if is_enabled():
    sampler = always_on.AlwaysOnSampler()
else:
    sampler = always_off.AlwaysOffSampler()

# Set the tracer to use the exporter
# Get the global singleton Tracer object
tracer = Tracer(exporter=ze, sampler=sampler)
tracer.span('root')
Example #16
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 azure.identity import ClientSecretCredential

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

tenant_id = "<tenant-id>"
client_id = "<client-id>"
client_secret = "<client-secret>"

credential = ClientSecretCredential(tenant_id=tenant_id,
                                    client_id=client_id,
                                    client_secret=client_secret)

tracer = Tracer(exporter=AzureExporter(
    credential=credential, connection_string="<your-connection-string>"),
                sampler=ProbabilitySampler(1.0))

with tracer.span(name='foo'):
    print('Hello, World!')
input(...)
Example #17
0
from dapr.clients import DaprClient

from opencensus.trace.tracer import Tracer
from opencensus.trace import time_event as time_event_module
from opencensus.ext.zipkin.trace_exporter import ZipkinExporter
from opencensus.trace.samplers import AlwaysOnSampler

ze = ZipkinExporter(service_name="python-example",
                    host_name='localhost',
                    port=9411,
                    endpoint='/api/v2/spans')

tracer = Tracer(exporter=ze, sampler=AlwaysOnSampler())

with tracer.span(name="main") as span:
    with DaprClient(tracer=tracer) as d:

        num_messages = 2

        for i in range(num_messages):
            # Create a typed message with content type and body
            resp = d.invoke_method(
                'invoke-receiver',
                'say',
                data=json.dumps({
                    'id': i,
                    'message': 'hello world'
                }),
            )
            # Print the response
Example #18
0
class APIService():
    def __init__(self, flask_app, logger):
        self.app = flask_app
        self.log = logger
        self.api = Api(self.app)
        self.is_terminating = False
        self.func_properties = {}
        self.func_request_counts = {}
        self.api_prefix = getenv('API_PREFIX')
        self.tracer = None

        self.api_task_manager = TaskManager()
        signal.signal(signal.SIGINT, self.initialize_term)

        # Add health check endpoint
        self.app.add_url_rule(self.api_prefix + '/',
                              view_func=self.health_check,
                              methods=['GET'])
        print("Adding url rule: " + self.api_prefix + '/')
        # Add task endpoint
        self.api.add_resource(
            Task,
            self.api_prefix + '/task/<id>',
            resource_class_kwargs={'task_manager': self.api_task_manager})
        print("Adding url rule: " + self.api_prefix + '/task/<int:taskId>')

        if getenv('APPINSIGHTS_INSTRUMENTATIONKEY', None):
            azure_exporter = AzureExporter(
                connection_string='InstrumentationKey=' +
                str(getenv('APPINSIGHTS_INSTRUMENTATIONKEY')))

            sampling_rate = getenv('TRACE_SAMPLING_RATE', None)
            if not sampling_rate:
                sampling_rate = 1.0

            self.middleware = FlaskMiddleware(
                self.app,
                exporter=azure_exporter,
                sampler=ProbabilitySampler(rate=float(sampling_rate)),
            )

            self.tracer = Tracer(
                exporter=AzureExporter(
                    connection_string='InstrumentationKey=' +
                    str(getenv('APPINSIGHTS_INSTRUMENTATIONKEY'))),
                sampler=ProbabilitySampler(rate=float(sampling_rate)),
            )

        self.app.before_request(self.before_request)

    def health_check(self):
        print("Health check call successful.")
        return 'Health check OK'

    def api_func(self,
                 is_async,
                 api_path,
                 methods,
                 request_processing_function,
                 maximum_concurrent_requests,
                 content_types=None,
                 content_max_length=None,
                 trace_name=None,
                 *args,
                 **kwargs):
        def decorator_api_func(func):
            if not self.api_prefix + api_path in self.func_properties:
                self.func_properties[self.api_prefix + api_path] = {
                    MAX_REQUESTS_KEY_NAME: maximum_concurrent_requests,
                    CONTENT_TYPE_KEY_NAME: content_types,
                    CONTENT_MAX_KEY_NAME: content_max_length
                }
                self.func_request_counts[self.api_prefix + api_path] = 0

            @wraps(func)
            def api(*args, **kwargs):
                internal_args = {"func": func, "api_path": api_path}

                if request_processing_function:
                    return_values = request_processing_function(request)
                    combined_kwargs = {
                        **internal_args,
                        **kwargs,
                        **return_values
                    }
                else:
                    combined_kwargs = {**internal_args, **kwargs}

                if is_async:
                    task_info = self.api_task_manager.AddTask(request)
                    taskId = str(task_info['TaskId'])
                    combined_kwargs["taskId"] = taskId

                    self.wrap_async_endpoint(trace_name, *args,
                                             **combined_kwargs)
                    return 'TaskId: ' + taskId
                else:
                    return self.wrap_sync_endpoint(trace_name, *args,
                                                   **combined_kwargs)

            api.__name__ = 'api_' + api_path.replace('/', '')
            print("Adding url rule: " + self.api_prefix + api_path + ", " +
                  api.__name__)
            self.app.add_url_rule(self.api_prefix + api_path,
                                  view_func=api,
                                  methods=methods,
                                  provide_automatic_options=True)

        return decorator_api_func

    def api_async_func(self,
                       api_path,
                       methods,
                       request_processing_function=None,
                       maximum_concurrent_requests=None,
                       content_types=None,
                       content_max_length=None,
                       trace_name=None,
                       *args,
                       **kwargs):
        is_async = True
        return self.api_func(is_async, api_path, methods,
                             request_processing_function,
                             maximum_concurrent_requests, content_types,
                             content_max_length, trace_name, *args, **kwargs)

    def api_sync_func(self,
                      api_path,
                      methods,
                      request_processing_function=None,
                      maximum_concurrent_requests=None,
                      content_types=None,
                      content_max_length=None,
                      trace_name=None,
                      *args,
                      **kwargs):
        is_async = False
        return self.api_func(is_async, api_path, methods,
                             request_processing_function,
                             maximum_concurrent_requests, content_types,
                             content_max_length, trace_name, *args, **kwargs)

    def initialize_term(self, signum, frame):
        print('Signal handler called with signal: ' + signum)
        print(
            'SIGINT received, service is terminating and will no longer accept requests.'
        )
        self.is_terminating = True

    def before_request(self):
        # Don't accept a request if SIGTERM has been called on this instance.
        if (self.is_terminating):
            print('Process is being terminated. Request has been denied.')
            abort(503, {'message': 'Service is busy, please try again later.'})

        if request.path in self.func_properties:
            if (self.func_properties[request.path][CONTENT_TYPE_KEY_NAME]
                    and not request.content_type in self.func_properties[
                        request.path][CONTENT_TYPE_KEY_NAME]):
                print('Invalid content type. Request has been denied.')
                abort(
                    401, {
                        'message':
                        'Content-type must be ' + self.func_properties[
                            request.path][CONTENT_TYPE_KEY_NAME]
                    })

            if (self.func_properties[request.path][CONTENT_MAX_KEY_NAME]
                    and request.content_length >
                    self.func_properties[request.path][CONTENT_MAX_KEY_NAME]):
                print('Request is too large. Request has been denied.')
                abort(
                    413, {
                        'message':
                        'Request content too large (' +
                        str(request.content_length) +
                        "). Must be smaller than: " + str(self.func_properties[
                            request.path][CONTENT_MAX_KEY_NAME])
                    })

            denied_request = 0
            if (self.func_request_counts[request.path] + 1 >
                    self.func_properties[request.path][MAX_REQUESTS_KEY_NAME]):
                print('Current requests: ' +
                      str(self.func_request_counts[request.path] + 1))
                print('Max requests: ' + str(self.func_properties[request.path]
                                             [MAX_REQUESTS_KEY_NAME]))
                denied_request = 1

                print('Service is busy. Request has been denied.')
                abort(503,
                      {'message': 'Service is busy, please try again later.'})

            if (disable_request_metric == 'False'):
                self.log.track_metric(
                    APP_INSIGHTS_REQUESTS_KEY_NAME + request.path,
                    denied_request)

    def increment_requests(self, api_path):
        self.func_request_counts[self.api_prefix + api_path] += 1

    def decrement_requests(self, api_path):
        self.func_request_counts[self.api_prefix + api_path] -= 1

    def wrap_sync_endpoint(self, trace_name=None, *args, **kwargs):
        if (self.tracer):
            if (not trace_name):
                api_path = kwargs['api_path']
                trace_name = api_path

            with self.tracer.span(name=trace_name) as span:
                return self._execute_func_with_counter(*args, **kwargs)
        else:
            return self._execute_func_with_counter(*args, **kwargs)

    def wrap_async_endpoint(self, trace_name=None, *args, **kwargs):
        if (self.tracer):
            if (not trace_name):
                api_path = kwargs['api_path']
                trace_name = api_path

            with self.tracer.span(name=trace_name) as span:
                self._create_and_execute_thread(*args, **kwargs)
        else:
            self._create_and_execute_thread(*args, **kwargs)

    def _create_and_execute_thread(self, *args, **kwargs):
        kwargs['request'] = request
        thread = Thread(target=self._execute_func_with_counter,
                        args=args,
                        kwargs=kwargs)
        thread.start()

    def _log_and_fail_exeception(self, **kwargs):
        if ('taskId' in kwargs):
            taskId = kwargs['taskId']
            if taskId:
                self.log.log_exception(sys.exc_info()[0], taskId)
                self.api_task_manager.FailTask(taskId,
                                               'Task failed - try again')
            else:
                self.log.log_exception(sys.exc_info()[0])
        else:
            self.log.log_exception(sys.exc_info()[0])

    def _execute_func_with_counter(self, *args, **kwargs):
        func = kwargs['func']
        api_path = kwargs['api_path']

        self.increment_requests(api_path)
        try:
            r = func(*args, **kwargs)
            return r
        except HTTPException as e:
            self._log_and_fail_exeception(**kwargs)
            return e
        except:
            print(sys.exc_info()[0])
            self._log_and_fail_exeception(**kwargs)
            abort(500)
        finally:
            self.decrement_requests(api_path)
Example #19
0
# Copyright 2019, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.

import requests

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.tracer import Tracer

if __name__ == '__main__':
    config_integration.trace_integrations(['requests'])
    # TODO: you need to specify the instrumentation key in the
    # APPINSIGHTS_INSTRUMENTATIONKEY environment variable.
    tracer = Tracer(exporter=AzureExporter())
    with tracer.span(name='parent'):
        with tracer.span(name='child'):
            response = requests.get(url='http://localhost:8080/')
            print(response.status_code)
            print(response.text)
Example #20
0
from opencensus.trace.tracer import Tracer


config_integration.trace_integrations(['logging'])

logger = logging.getLogger(__name__)

handler = AzureLogHandler(connection_string='InstrumentationKey=<Your Key>')

handler.setFormatter(logging.Formatter('%(traceId)s %(spanId)s %(message)s'))

logger.addHandler(handler)

tracer = Tracer(
    exporter=AzureExporter(connection_string='InstrumentationKey=<Your Key>'),
    sampler=ProbabilitySampler(1.0)

)

logger.warning('Before the span')
with tracer.span(name='azka_test_1'):
    logger.warning('In the span azka_test_1')
with tracer.span(name='azka_test_2'):
    logger.warning('In the span azka_test_2')
logger.warning('After the span')


input("...asdfd")

##traces
## | where message contains 'azka_test'
logger.addHandler(handler)

exporter = metrics_exporter.new_metrics_exporter(connection_string=cs)

config_integration.trace_integrations(['requests'])
tracer = Tracer(
    exporter=AzureExporter(connection_string=cs),
    sampler=ProbabilitySampler(1.0),
)
logger.error("Ale błąd")

for i in range(10):
    print(psutil.virtual_memory())
    time.sleep(5)
    with tracer.span(name='parent'):
        response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')
        print(response.status_code)

        properties = {
            'custom_dimensions': {
                'key_1': 'value_1',
                'key_2': 'value_2'
            }
        }
        try:
            result = 1 / 0  # generate a ZeroDivisionError
        except Exception as exc:
            logger.exception(exc, extra=properties)

logger.warning("Komunikat WARNING")
Example #22
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.

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

config_integration.trace_integrations(['logging'])

logger = logging.getLogger(__name__)

# TODO: you need to specify the instrumentation key in the
# APPINSIGHTS_INSTRUMENTATIONKEY environment variable.
handler = AzureLogHandler()
logger.addHandler(handler)

tracer = Tracer(exporter=AzureExporter(), sampler=ProbabilitySampler(1.0))

logger.warning('Before the span')
with tracer.span(name='test'):
    logger.warning('In the span')
logger.warning('After the span')
Example #23
0
        exporter=EXPORTER,
        sampler=SAMPLER,
    )

    # Add tracing for PostgreSQL
    config_integration.trace_integrations(['postgresql'])

    # Configure logging from settings.py
    logging.config.dictConfig(getattr(django.conf.settings, 'LOGGING', {}))

    # Add logging integration
    config_integration.trace_integrations(['logging'])
    logger = logging.getLogger(__name__)

    if getattr(django.conf.settings, 'DEBUG'):
        try:
            from logging_tree import printout
            printout()
        except:
            pass  # optional logging_tree not in venv.

    # Run with tracing
    # TODO: Currently the manage.py command is showing as a dependency. Can I turn it into the node itself?
    # TODO: tracemanage.py node is showing with 0 calls and 0ms
    with TRACER.span(name='manage.py/{0}'.format(sys.argv[1])) as span:
        span.span_kind = span_module.SpanKind.CLIENT
        TRACER.add_attribute_to_current_span("http.method", "CLI")
        TRACER.add_attribute_to_current_span(
            "http.route", 'manage.py/{0}'.format(sys.argv[1]))
        execute_from_command_line(sys.argv)
def create_dependency(name=name, message=message):
    tracer = Tracer(exporter=AzureExporter(
        connection_string='InstrumentationKey=%s' % (instrument_key)),
                    sampler=ProbabilitySampler(1.0))
    with tracer.span(name=name):
        print(message)