How to use the ddtrace.internal.logger.get_logger 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 / internal / test_logger.py View on Github external
def test_logger_log(self):
        """
        When calling `DDLogger` log methods
            We call `DDLogger.handle` with the expected log record
        """
        log = get_logger('test.logger')

        # -- NOTSET
        # By default no level is set so we only get warn, error, and critical messages
        self.assertEqual(log.level, logging.NOTSET)
        # `log.warn`, `log.warning`, `log.error`, `log.exception`, `log.critical`, `log.fatal`
        self.assert_log_records(log, ['WARNING', 'WARNING', 'ERROR', 'ERROR', 'CRITICAL', 'CRITICAL'])

        # -- CRITICAL
        log.setLevel(logging.CRITICAL)
        # `log.critical`, `log.fatal`
        self.assert_log_records(log, ['CRITICAL', 'CRITICAL'])

        # -- ERROR
        log.setLevel(logging.ERROR)
        # `log.error`, `log.exception`, `log.critical`, `log.fatal`
        self.assert_log_records(log, ['ERROR', 'ERROR', 'CRITICAL', 'CRITICAL'])
github DataDog / dd-trace-py / ddtrace / contrib / django / templates.py View on Github external
"""
code to measure django template rendering.
"""
# project
from ...ext import SpanTypes
from ...internal.logger import get_logger

# 3p
from django.template import Template

log = get_logger(__name__)

RENDER_ATTR = '_datadog_original_render'


def patch_template(tracer):
    """ will patch django's template rendering function to include timing
        and trace information.
    """

    # FIXME[matt] we're patching the template class here. ideally we'd only
    # patch so we can use multiple tracers at once, but i suspect this is fine
    # in practice.
    if getattr(Template, RENDER_ATTR, None):
        log.debug('already patched')
        return
github DataDog / dd-trace-py / ddtrace / monkey.py View on Github external
It can monkey patch supported standard libraries and third party modules.
A patched module will automatically report spans with its default configuration.

A library instrumentation can be configured (for instance, to report as another service)
using Pin. For that, check its documentation.
"""
import importlib
import sys
import threading

from ddtrace.vendor.wrapt.importer import when_imported

from .internal.logger import get_logger


log = get_logger(__name__)

# Default set of modules to automatically patch or not
PATCH_MODULES = {
    'asyncio': False,
    'boto': True,
    'botocore': True,
    'bottle': False,
    'cassandra': True,
    'celery': True,
    'consul': True,
    'elasticsearch': True,
    'algoliasearch': True,
    'futures': False,  # experimental propagation
    'grpc': True,
    'mongoengine': True,
    'mysql': True,
github DataDog / dd-trace-py / ddtrace / settings / hooks.py View on Github external
import collections
from copy import deepcopy

from ..internal.logger import get_logger
from ..span import Span

log = get_logger(__name__)


class Hooks(object):
    """
    Hooks configuration object is used for registering and calling hook functions

    Example::

        @config.falcon.hooks.on('request')
        def on_request(span, request, response):
            pass
    """
    __slots__ = ['_hooks']

    def __init__(self):
        self._hooks = collections.defaultdict(set)
github DataDog / dd-trace-py / ddtrace / contrib / django / cache.py View on Github external
from functools import wraps

from django.conf import settings as django_settings

from ...internal.logger import get_logger
from .conf import settings, import_from_string
from .utils import quantize_key_values, _resource_from_cache_prefix


log = get_logger(__name__)

# code instrumentation
DATADOG_NAMESPACE = '__datadog_original_{method}'
TRACED_METHODS = [
    'get',
    'set',
    'add',
    'delete',
    'incr',
    'decr',
    'get_many',
    'set_many',
    'delete_many',
]

# standard tags
github DataDog / dd-trace-py / ddtrace / contrib / pylibmc / client.py View on Github external
import pylibmc

# project
import ddtrace
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...ext import SpanTypes, memcached, net
from ...internal.logger import get_logger
from ...settings import config
from .addrs import parse_addresses


# Original Client class
_Client = pylibmc.Client


log = get_logger(__name__)


class TracedClient(ObjectProxy):
    """ TracedClient is a proxy for a pylibmc.Client that times it's network operations. """

    def __init__(self, client=None, service=memcached.SERVICE, tracer=None, *args, **kwargs):
        """ Create a traced client that wraps the given memcached client.

        """
        # The client instance/service/tracer attributes are kept for compatibility
        # with the old interface: TracedClient(client=pylibmc.Client(['localhost:11211']))
        # TODO(Benjamin): Remove these in favor of patching.
        if not isinstance(client, _Client):
            # We are in the patched situation, just pass down all arguments to the pylibmc.Client
            # Note that, in that case, client isn't a real client (just the first argument)
            client = _Client(client, *args, **kwargs)
github DataDog / dd-trace-py / ddtrace / propagation / http.py View on Github external
from ..context import Context
from ..internal.logger import get_logger

from .utils import get_wsgi_header

log = get_logger(__name__)

# HTTP headers one should set for distributed tracing.
# These are cross-language (eg: Python, Go and other implementations should honor these)
HTTP_HEADER_TRACE_ID = 'x-datadog-trace-id'
HTTP_HEADER_PARENT_ID = 'x-datadog-parent-id'
HTTP_HEADER_SAMPLING_PRIORITY = 'x-datadog-sampling-priority'
HTTP_HEADER_ORIGIN = 'x-datadog-origin'


# Note that due to WSGI spec we have to also check for uppercased and prefixed
# versions of these headers
POSSIBLE_HTTP_HEADER_TRACE_IDS = frozenset(
    [HTTP_HEADER_TRACE_ID, get_wsgi_header(HTTP_HEADER_TRACE_ID)]
)
POSSIBLE_HTTP_HEADER_PARENT_IDS = frozenset(
    [HTTP_HEADER_PARENT_ID, get_wsgi_header(HTTP_HEADER_PARENT_ID)]
github DataDog / dd-trace-py / ddtrace / contrib / pylons / middleware.py View on Github external
from webob import Request
from pylons import config

from .renderer import trace_rendering
from .constants import CONFIG_MIDDLEWARE

from ...compat import reraise
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...ext import SpanTypes, http
from ...internal.logger import get_logger
from ...propagation.http import HTTPPropagator
from ...settings import config as ddconfig


log = get_logger(__name__)


class PylonsTraceMiddleware(object):

    def __init__(self, app, tracer, service='pylons', distributed_tracing=True):
        self.app = app
        self._service = service
        self._distributed_tracing = distributed_tracing
        self._tracer = tracer

        # register middleware reference
        config[CONFIG_MIDDLEWARE] = self

        # add template tracing
        trace_rendering()
github DataDog / dd-trace-py / ddtrace / contrib / pymemcache / client.py View on Github external
MemcacheClientError,
    MemcacheServerError,
    MemcacheUnknownCommandError,
    MemcacheUnknownError,
    MemcacheIllegalInputError,
)

# project
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...compat import reraise
from ...ext import SpanTypes, net, memcached as memcachedx
from ...internal.logger import get_logger
from ...pin import Pin
from ...settings import config

log = get_logger(__name__)


# keep a reference to the original unpatched clients
_Client = Client


class WrappedClient(wrapt.ObjectProxy):
    """Wrapper providing patched methods of a pymemcache Client.

    Relevant connection information is obtained during initialization and
    attached to each span.

    Keys are tagged in spans for methods that act upon a key.
    """

    def __init__(self, *args, **kwargs):
github DataDog / dd-trace-py / ddtrace / internal / import_hooks.py View on Github external
being loaded and re-calling `__import__` for the module to trigger the other finders.

4) Reloading a module is a weird case that doesn't always trigger a module finder.


For these reasons we have decided to patch Python's internal module loading functions instead.
"""
import sys

from ..compat import PY3
from ..vendor import wrapt
from .logger import get_logger

__all__ = ['hooks', 'register_module_hook', 'patch', 'unpatch']

log = get_logger(__name__)


class ModuleHookRegistry(object):
    """
    Registry to keep track of all module import hooks defined
    """
    __slots__ = ('hooks', )

    def __init__(self):
        """
        Initialize a new registry
        """
        self.reset()

    def register(self, name, func):
        """