Example #1
0
def get_ls_tracer():
    tracer.configure(http_propagator=B3HTTPPropagator, settings={})
    tracer.set_tags(
        {
            "lightstep.service_name": os.getenv("LS_SERVICE_NAME"),
            "service.version": os.getenv("LS_SERVICE_VERSION"),
            "lightstep.access_token": os.getenv("LS_ACCESS_TOKEN"),
        }
    )
def test_configure_keeps_api_hostname_and_port():
    """
    Ensures that when calling configure without specifying hostname and port,
    previous overrides have been kept.
    """
    tracer = Tracer()
    assert tracer.writer._hostname == "localhost"
    assert tracer.writer._port == 8126
    tracer.configure(hostname="127.0.0.1", port=8127)
    assert tracer.writer._hostname == "127.0.0.1"
    assert tracer.writer._port == 8127
    tracer.configure(priority_sampling=True)
    assert tracer.writer._hostname == "127.0.0.1"
    assert tracer.writer._port == 8127
Example #3
0
    priority_sampling = os.environ.get("DATADOG_PRIORITY_SAMPLING")

    opts = {}

    if enabled and enabled.lower() == "false":
        opts["enabled"] = False
        patch = False
    if hostname:
        opts["hostname"] = hostname
    if port:
        opts["port"] = int(port)
    if priority_sampling:
        opts["priority_sampling"] = asbool(priority_sampling)

    if opts:
        tracer.configure(**opts)

    if not hasattr(sys, 'argv'):
        sys.argv = ['']

    if patch:
        update_patched_modules()
        from ddtrace import patch_all; patch_all(**EXTRA_PATCHED_MODULES) # noqa

    debug = os.environ.get("DATADOG_TRACE_DEBUG")
    if debug and debug.lower() == "true":
        tracer.debug_logging = True

    if 'DATADOG_ENV' in os.environ:
        tracer.set_tags({"env": os.environ["DATADOG_ENV"]})
Example #4
0
import os
import redis

from flask import Flask
from flask import request, redirect, render_template, url_for
from flask import Response

# Datadog tracing and metrics
from datadog import initialize, statsd
from ddtrace import tracer, patch_all

# If we're getting a DogStatD host (i.e. running in Kubernetes), initialize with it.
if "DOGSTATSD_HOST_IP" in os.environ:
  initialize(statsd_host = os.environ.get("DOGSTATSD_HOST_IP"))
  tracer.configure(hostname = os.environ.get("DOGSTATSD_HOST_IP"))

# Apply some base tags and patch for Datadog tracing.
patch_all()

redishost = 'redis-master'
if 'REDIS_HOST' in os.environ:
    redishost = os.environ.get('REDIS_HOST')

app = Flask(__name__)
app.redis = redis.StrictRedis(host=redishost, port=6379, db=0)

# Be super aggressive about saving for the development environment.
# This says save every second if there is at least 1 change.  If you use
# redis in production you'll want to read up on the redis persistence
# model.
app.redis.config_set('save', '1 1')
Example #5
0
        request_bodies='always',
    )

# Datadog
DATADOG_SETTINGS = {
    'host_name': env.str('DD_AGENT_HOST', None),
    'api_key': env.str('DATADOG_API_KEY', None),
    'app_key': env.str('DATADOG_APP_KEY', None),
}

if not DEBUG:
    tracer.configure(
        hostname=env.str('DD_AGENT_HOST'),
        port=env.str('DD_TRACE_AGENT_PORT'),
        settings={
            'FILTERS': [
                FilterRequestsOnUrl(
                    [r'http://api\\.nephrogo\\.com/health/', r'http://localhost:8080/health/'])
            ],
        }
    )
    config.django['service_name'] = 'nephrogo-api'
    config.django['instrument_databases'] = True
    config.django['instrument_caches'] = True
    config.django['trace_query_string'] = True
    config.django['analytics_enabled'] = True

    config.trace_headers([
        'user-agent',
        'transfer-encoding',
        'time-zone-name',
        'accept-encoding',
Example #6
0
from redis import Redis
import os

# Add and initialize Datadog monitoring.
from datadog import initialize, statsd
initialize(statsd_host=os.environ.get('DATADOG_HOST'))
from ddtrace import tracer
from ddtrace.contrib.flask import TraceMiddleware

app = Flask(__name__)
redis = Redis(host='redis', port=6379)

traced_app = TraceMiddleware(app,
                             tracer,
                             service="my-flask-app",
                             distributed_tracing=False)
tracer.configure(hostname='datadog')


@app.route('/')
def hello():
    # Increment the Datadog counter.
    statsd.increment('docker_compose_example.page.views')

    redis.incr('hits')
    return 'Hello World! I have been seen %s times.' % redis.get('hits')


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
Example #7
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.
import os
from ddtrace import tracer
from ddtrace.propagation.b3 import B3HTTPPropagator

tracer.configure(
    http_propagator=B3HTTPPropagator,
    hostname=os.environ['LIGHTSTEP_HOST'],
    port=os.environ['LIGHTSTEP_PORT'],
    https=os.environ['LIGHTSTEP_PLAINTEXT'] is not "true"
)
tracer.set_tags(
    {
        "lightstep.service_name": "emailservice",
        "lightstep.access_token": os.getenv("LIGHTSTEP_ACCESS_TOKEN"),
    }
)

from concurrent import futures
import argparse
import sys
import time
import grpc
from jinja2 import Environment, FileSystemLoader, select_autoescape, TemplateError
Example #8
0
#!/usr/bin/env python3
import os
import time

import requests
import yaml

from ddtrace import tracer
from ddtrace.propagation.b3 import B3HTTPPropagator


tracer.configure(http_propagator=B3HTTPPropagator, settings={})


def send_requests(destinations):
    with tracer.trace("send_requests"):
        for url in destinations:
            try:
                if "/order" in url:
                    res = requests.post(
                        url, data='{"donuts":[{"flavor":"cinnamon","quantity":1}]}'
                    )
                else:
                    res = requests.get(url)
                print(f"Request to {url}, got {len(res.content)} bytes")
            except Exception as e:
                print(f"Request to {url} failed {e}")


if __name__ == "__main__":
    config_file = os.environ.get("INTEGRATION_CONFIG_FILE")
Example #9
0
    propagate = False


logger = CustomLogger("fastapi")

logHandler = logging.StreamHandler()
formatter = CustomJsonFormatter()
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)

patch(fastapi=True, logging=True)

initialize(statsd_host=os.getenv("DATADOG_HOST"),
           statsd_port=8125,
           host_name="fastapi")
tracer.configure(hostname=os.getenv("DATADOG_HOST"), port=8126, enabled=True)

app = FastAPI()


@statsd.timed("fastapi.views.check.timer", tags=["function:do_check"])
def do_check():
    sleep(random())


@app.get("/check")
def check():
    statsd.increment("fastapi.views.check.count")
    logger.info("ServiceB check")
    try:
        if randint(1, 10) == 7:
Example #10
0
            trace_id = int(trace_context_data.get("x-datadog-trace-id"))

            # The reason I'm not using parent_id from the message is because
            # processing this message is not part of the span in the producer.
            # Rather it's the next span in a sequence. So I'm not setting
            # context.span_id, we want a new span. But they're both part of the
            # same trace still.
            if trace_id:
                return context.Context(trace_id=trace_id)

        return None


client = boto3.client("sqs")
sqs_context_extractor = SQSContextExtractor()
tracer.configure(settings={"FILTERS": [ProcessMessageFilter()]})


@tracer.wrap("consumer.poll")
def poll_queue():
    QUEUE_POLL_COUNT.inc()
    resp = client.receive_message(
        QueueUrl=os.environ.get("QUEUE_URL"),
        MessageAttributeNames=["All"],
    )

    if "Messages" not in resp:
        return

    for message in resp["Messages"]:
        context = sqs_context_extractor.process_message(message)
Example #11
0
from datadog import initialize, api
from flask import Flask, send_file, redirect
from ddtrace import tracer
from ddtrace.contrib.flask import TraceMiddleware

options = {'api_key': 'e1dbdaceaf7516f90ef9e2ad5546072e',
            'app_key': '25b8d433ca6e9ca99c1ee791e8ece8c67e6a0ec3'}

initialize(**options)

app = Flask(__name__)

the_spans = []

tracer.configure(hostname="127.0.0.1")
traced_app = TraceMiddleware(app, tracer, service="api", distributed_tracing=False)

@app.route(u'/ce')
def cause_exception():
    assert(1==3)
    return 'x'

@app.route(u'/tfs')
def trace_full_stack():
    try:
        connect_str = "dbname=ddhee user='******' host='localhost' " + \
                      "password='******'"
        # use our connection values to establish a connection
        conn = psycopg2.connect(connect_str)
        # create a psycopg2 cursor that can execute queries
Example #12
0
from flask import Flask
import logging
import sys
import os
import ddtrace.profile.auto
from ddtrace import tracer

tracer.configure(hostname=os.environ['DD_AGENT_HOST'], )

# Have flask use stdout as the logger
main_logger = logging.getLogger()
main_logger.setLevel(logging.DEBUG)
c = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
c.setFormatter(formatter)
main_logger.addHandler(c)

app = Flask(__name__)


@tracer.wrap()
@app.route('/')
def api_entry():
    return 'Entrypoint to the Application'


@tracer.wrap()
@app.route('/api/apm')
def apm_endpoint():
    return 'Getting APM Started'
Example #13
0
        with tracer.trace("1"):
            with tracer.trace("2"):
                with tracer.trace("3"):
                    with tracer.trace("4"):
                        with tracer.trace("5"):
                            pass
                        with tracer.trace("6"):
                            pass
                    with tracer.trace("7"):
                        pass
                with tracer.trace("8"):
                    pass
            with tracer.trace("9"):
                pass
    dt = pyperf.perf_counter() - t0
    return dt


# append a filter to drop traces so that no traces are encoded and sent to the agent
class DropTraces(TraceFilter):
    def process_trace(self, trace):
        return


if __name__ == "__main__":
    runner = pyperf.Runner()
    tracer.configure(settings={"FILTERS": [DropTraces()]})
    for variant in VARIANTS:
        name = "|".join(f"{k}:{v}" for (k, v) in variant.items())
        runner.bench_time_func("scenario:tracer|" + name, time_trace, variant)