def init_opentracing_tracer(tracer, **kwargs): if tracer == OPENTRACING_BASIC: from basictracer import BasicTracer # noqa recorder = kwargs.get('recorder') sampler = kwargs.get('sampler') opentracing.tracer = BasicTracer(recorder=recorder, sampler=sampler) elif tracer == OPENTRACING_INSTANA: import instana.options as InstanaOpts import instana.tracer # noqa service = kwargs.pop('service', os.environ.get('OPENTRACING_INSTANA_SERVICE')) log_level = kwargs.pop('log_level', logging.INFO) instana.tracer.init( InstanaOpts.Options(service=service, log_level=log_level, **kwargs)) elif tracer == OPENTRACING_LIGHTSTEP: import lightstep # Get Lightstep specific config vars component_name = kwargs.pop( 'component_name', os.environ.get('OPENTRACING_LIGHTSTEP_COMPONENT_NAME')) access_token = kwargs.pop( 'access_token', os.environ.get('OPENTRACING_LIGHTSTEP_ACCESS_TOKEN')) collector_host = kwargs.pop( 'collector_host', os.environ.get('OPENTRACING_LIGHTSTEP_COLLECTOR_HOST', 'collector.lightstep.com')) collector_port = kwargs.pop( 'collector_port', int(os.environ.get('OPENTRACING_LIGHTSTEP_COLLECTOR_PORT', 443))) verbosity = kwargs.pop( 'verbosity', int(os.environ.get('OPENTRACING_LIGHTSTEP_VERBOSITY', 0))) if not access_token: logger.warn('Initializing LighStep tracer with no access_token!') opentracing.tracer = lightstep.Tracer(component_name=component_name, access_token=access_token, collector_host=collector_host, collector_port=collector_port, verbosity=verbosity, **kwargs) elif tracer == OPENTRACING_JAEGER: from jaeger_client import Config service_name = kwargs.pop( 'service_name', os.environ.get('OPENTRACING_JAEGER_SERVICE_NAME')) config = kwargs.pop('config', {}) jaeger_config = Config(config=config, service_name=service_name) opentracing.tracer = jaeger_config.initialize_tracer() else: opentracing.tracer = opentracing.Tracer()
def build_tracer(): tracer_name = args.tracer if args.trace and tracer_name == "vanilla": logging.info("We're using the python tracer.") import lightstep return lightstep.Tracer( component_name='isaac_service', collector_port=SATELLITE_PORTS[0], collector_host='localhost', collector_encryption='none', use_http=True, access_token='developer', periodic_flush_seconds=REPORTING_PERIOD, max_span_records=MAX_BUFFERED_SPANS, ) elif args.trace and tracer_name == "cpp": logging.info("We're using the python-cpp tracer.") import lightstep_streaming return lightstep_streaming.Tracer( component_name='isaac_service', access_token='developer', use_stream_recorder=True, collector_plaintext=True, satellite_endpoints=[{ 'host': 'localhost', 'port': p } for p in SATELLITE_PORTS], max_buffered_spans=MAX_BUFFERED_SPANS, reporting_period=REPORTING_PERIOD * 10**6, # s --> us ) logging.info("We're using a NoOp tracer.") return opentracing.Tracer()
def opentracing_tween_factory(handler, registry): ''' The factory method is called once, and we thus retrieve the settings as defined on the global configuration. We set the 'opentracing_tracer' in the settings to, for further reference and usage. ''' base_tracer = registry.settings.get('ot.base_tracer', opentracing.Tracer()) traced_attrs = aslist(registry.settings.get('ot.traced_attributes', [])) trace_all = asbool(registry.settings.get('ot.trace_all', False)) if 'ot.base_tracer_func' in registry.settings: base_tracer_func = registry.settings.get('ot.base_tracer_func') base_tracer = _call_base_tracer_func(base_tracer_func, registry.settings) tracer = PyramidTracer(base_tracer, trace_all) registry.settings['ot.tracer'] = tracer def opentracing_tween(req): # if tracing for all requests is disabled, continue with the # normal handlers flow and return immediately. if not trace_all: return handler(req) tracer._apply_tracing(req, traced_attrs) try: res = handler(req) except: tracer._finish_tracing(req, error=True) raise tracer._finish_tracing(req) return res return opentracing_tween
def build_tracer(command, tracer_name, port): if command['Trace'] and tracer_name == "vanilla": logging.info("We're using the python tracer.") import lightstep return lightstep.Tracer( component_name='isaac_service', collector_port=port, collector_host='localhost', collector_encryption='none', use_http=True, access_token='developer', # these are much more aggressive than the defaults # but are common in production periodic_flush_seconds=REPORTING_PERIOD / 1000, max_span_records=MAX_BUFFERED_SPANS, ) elif command['Trace'] and tracer_name == "cpp": logging.info("We're using the python-cpp tracer.") import lightstep_native return lightstep_native.Tracer( component_name='isaac_service', access_token='developer', use_stream_recorder=True, collector_plaintext=True, satellite_endpoints=[{ 'host': 'localhost', 'port': p } for p in range(port, port + NUM_SATELLITES)], max_buffered_spans=MAX_BUFFERED_SPANS, reporting_period=REPORTING_PERIOD, ) logging.info("We're using a NoOp tracer.") return opentracing.Tracer()
def __init__(self, get_response=None): ''' TODO: ANSWER Qs - Is it better to place all tracing info in the settings file, or to require a tracing.py file with configurations? - Also, better to have try/catch with empty tracer or just fail fast if there's no tracer specified ''' if hasattr(settings, 'OPENTRACING_TRACER'): self._tracer = settings.OPENTRACING_TRACER else: self._tracer = opentracing.Tracer()
from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.view import view_config import opentracing from pyramid_opentracing import PyramidTracer # Pass a specific Tracer instance to PyramidTracer() tracer = PyramidTracer(opentracing.Tracer()) @view_config(route_name='root', renderer='json') def server_index(request): return {'message': 'Hello world!'} @view_config(route_name='simple', renderer='json') @tracer.trace('method') def server_simple(request): return {'message': 'This is a simple traced request.'} @view_config(route_name='log', renderer='json') @tracer.trace() def server_log(request): span = tracer.get_span(request) span.log_event('Hello, World!') return {'message': 'Something was logged'} if __name__ == '__main__':
import opentracing from opentracing.scope_managers.tornado import TornadoScopeManager from opentracing_instrumentation.request_context import ( get_current_span, span_in_stack_context, RequestContext, RequestContextManager, ) from mock import patch from tornado import gen from tornado import stack_context from tornado.testing import AsyncTestCase, gen_test @patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager())) class TornadoTraceContextTest(AsyncTestCase): @gen_test def test_http_fetch(self): span1 = 'Bender is great!' span2 = 'Fry is dumb!' @gen.coroutine def check(span_to_check): assert get_current_span() == span_to_check with self.assertRaises(Exception): # passing mismatching spans yield run_coroutine_with_span(span1, check, span2) @gen.coroutine def nested(nested_span_to_check, span_to_check):
from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler from tornado import gen import opentracing import tornado_opentracing from tornado_opentracing.scope_managers import TornadoScopeManager tornado_opentracing.init_tracing() # Your OpenTracing-compatible tracer here. tracer = opentracing.Tracer(scope_manager=TornadoScopeManager()) class MainHandler(RequestHandler): def get(self): self.write({'status': 'ok'}) class StoryHandler(RequestHandler): @gen.coroutine def get(self, story_id): if int(story_id) == 0: raise ValueError('invalid value passed') tracer.active_span.set_tag('processed', True) self.write({'status': 'fetched'})
def noop_span() -> opentracing.Span: return opentracing.Tracer()._noop_span
def noop_span() -> opentracing.Span: """Return a span that does nothing when traced.""" return opentracing.Tracer()._noop_span
from flask import (Flask, request) import opentracing from flask_opentracing import FlaskTracer app = Flask(__name__) test_app = app.test_client() empty_tracer = opentracing.Tracer() tracer_all = FlaskTracer(empty_tracer, True, app, ['url']) tracer = FlaskTracer(empty_tracer) tracer_deferred = FlaskTracer(lambda: opentracing.Tracer(), True, app, ['url']) def flush_spans(tcr): for req in tcr._current_spans: tcr._current_spans[req].finish() tcr._current_spans = {} @app.route('/test') def check_test_works(): return "Success" @app.route('/another_test') @tracer.trace('url', 'url_rule') def decorated_fn(): return "Success again" @app.route('/wire')
def init_opentracing_tracer(tracer, **kwargs): if tracer == OPENTRACING_BASIC: from basictracer import BasicTracer # noqa recorder = kwargs.get('recorder') sampler = kwargs.get('sampler') opentracing.tracer = BasicTracer(recorder=recorder, sampler=sampler) elif tracer == OPENTRACING_INSTANA: import instana # noqa elif tracer == OPENTRACING_LIGHTSTEP: import lightstep # Get Lightstep specific config vars component_name = kwargs.pop( 'component_name', os.environ.get('OPENTRACING_LIGHTSTEP_COMPONENT_NAME')) access_token = kwargs.pop( 'access_token', os.environ.get('OPENTRACING_LIGHTSTEP_ACCESS_TOKEN')) collector_host = kwargs.pop( 'collector_host', os.environ.get('OPENTRACING_LIGHTSTEP_COLLECTOR_HOST', 'collector.lightstep.com')) collector_port = kwargs.pop( 'collector_port', int(os.environ.get('OPENTRACING_LIGHTSTEP_COLLECTOR_PORT', 443))) verbosity = kwargs.pop( 'verbosity', int(os.environ.get('OPENTRACING_LIGHTSTEP_VERBOSITY', 0))) scheme = kwargs.pop( 'collector_scheme', os.environ.get('OPENTRACING_LIGHTSTEP_COLLECTOR_SCHEME', 'https')) if not access_token: logger.warning( 'Initializing LightStep tracer with no access_token!') collector_encryption = "tls" if scheme == "http": collector_encryption = "none" if 'collector_encryption' in kwargs: collector_encryption = kwargs.pop('collector_encryption', collector_encryption) opentracing.tracer = lightstep.Tracer( component_name=component_name, access_token=access_token, collector_host=collector_host, collector_port=collector_port, collector_encryption=collector_encryption, verbosity=verbosity, **kwargs) elif tracer == OPENTRACING_JAEGER: from jaeger_client import Config service_name = kwargs.pop( 'service_name', os.environ.get('OPENTRACING_JAEGER_SERVICE_NAME')) config = kwargs.pop('config', {}) jaeger_config = Config(config=config, service_name=service_name) opentracing.tracer = jaeger_config.initialize_tracer() else: opentracing.tracer = opentracing.Tracer() return opentracing.tracer
def test_tracer(self): tracer = opentracing.Tracer() tracing = SanicTracing(tracer=tracer) assert tracing.tracer is tracer assert tracing._trace_all_requests is False
def test_tracer(self): tracer = opentracing.Tracer() tracing = BottleTracing(tracer) self.assertIs(tracing.tracer, tracer) self.assertFalse(tracing._trace_all_requests)
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import absolute_import from mock import patch import opentracing from opentracing.scope_managers import ThreadLocalScopeManager from opentracing_instrumentation.local_span import func_span from opentracing_instrumentation.client_hooks._dbapi2 import db_span, _COMMIT from opentracing_instrumentation.client_hooks._singleton import singleton from opentracing_instrumentation import span_in_context @patch('opentracing.tracer', new=opentracing.Tracer(ThreadLocalScopeManager())) def test_func_span_without_parent(): with func_span('test', require_active_trace=False) as span: assert span is not None with func_span('test', require_active_trace=True) as span: assert span is None def test_func_span(): tracer = opentracing.tracer span = tracer.start_span(operation_name='parent') with span_in_context(span=span): with func_span('test') as child_span: assert span is child_span with func_span('test', tags={'x': 'y'}) as child_span: assert span is child_span
from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.view import view_config import opentracing from pyramid_opentracing import PyramidTracer tracer = PyramidTracer( opentracing.Tracer(), # Pass a specific Tracer instance to PyramidTracer() operation_name_func=lambda req: 'Test-' + req.method, # optional ) @view_config(route_name='root', renderer='json') def server_index(request): return {'message': 'Hello world!'} @view_config(route_name='simple', renderer='json') @tracer.trace('method') def server_simple(request): return {'message': 'This is a simple traced request.'} @view_config(route_name='log', renderer='json') @tracer.trace() def server_log(request): span = tracer.get_span(request) span.log_event('Hello, World!') return {'message': 'Something was logged'}
import urllib2 from pyramid.view import view_config from pyramid.config import Configurator import opentracing import pyramid_opentracing from waitress import serve tracing = pyramid_opentracing.PyramidTracing(opentracing.Tracer()) # Client @view_config(route_name='client_simple', renderer='json') @tracing.trace() def client_simple(request): url = 'http://127.0.0.1:8080/server/simple' new_request = urllib2.Request(url) inject_as_headers(tracing, tracing.tracer.active_span, new_request) try: urllib2.urlopen(new_request) return {'message': 'Made a simple request'} except urllib2.URLError as e: return {'error': e} @view_config(route_name='client_log', renderer='json') @tracing.trace() def client_log(request): url = 'http://127.0.0.1:8080/server/log' new_request = urllib2.Request(url)
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'test_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'test_site.wsgi.application' # OpenTracing settings OPENTRACING_TRACE_ALL = True OPENTRACING_TRACER = django_opentracing.DjangoTracer(opentracing.Tracer()) OPENTRACING_TRACED_ATTRIBUTES = ['META', 'FAKE_ATTRIBUTE']
from flask import (Flask, request) import opentracing from flask_opentracing import FlaskTracer app = Flask(__name__) test_app = app.test_client() empty_tracer = opentracing.Tracer() tracer_all = FlaskTracer(empty_tracer, True, app, ['url']) tracer = FlaskTracer(empty_tracer) def flush_spans(tcr): for req in tcr._current_spans: tcr._current_spans[req].finish() tcr._current_spans = {} @app.route('/test') def check_test_works(): return "Success" @app.route('/another_test') @tracer.trace('url', 'url_rule') def decorated_fn(): return "Success again" @app.route('/wire') def send_request():
import tornado.stack_context import tornado.concurrent from tornado import gen from tornado.testing import AsyncTestCase, gen_test from opentracing_instrumentation import traced_function from opentracing_instrumentation import span_in_stack_context patch_object = mock.patch.object def extract_call_site_tag(span, *_, **kwargs): if 'call_site_tag' in kwargs: span.set_tag('call_site_tag', kwargs['call_site_tag']) @mock.patch('opentracing.tracer', opentracing.Tracer(TornadoScopeManager())) class TracedFuctionDecoratorTest(AsyncTestCase): @gen_test def test_no_arg_decorator(self): class SomeClient(object): @traced_function @gen.coroutine def func1(self, param1): assert param1 == 123 raise tornado.gen.Return('oh yeah') @traced_function def func1_1(self, param1): assert param1 == 123 return 'oh yeah' # not a co-routine
import datetime import redis import opentracing import redis_opentracing # Your OpenTracing-compatible tracer here. tracer = opentracing.Tracer() if __name__ == '__main__': client = redis.StrictRedis() # By default, init_tracing() traces all Redis commands. redis_opentracing.init_tracing(tracer) with tracer.start_active_span('main_span'): # Traced as a SET command, # with main_span as implicit parent. client.set('last_access', datetime.datetime.now()) # Traced as a MULTI command with # SET key:00 what # SET foo:01 bar pipe = client.pipeline() pipe.set('key:00', 'what') pipe.set('foo:01', 'bar') print(pipe.execute())
service_host=args.host, service_port=args.port) else: return lightstep.tracer.init_tracer( group_name=args.group_name, access_token=args.token, service_host=args.host, service_port=args.port, secure=False) if __name__ == '__main__': print 'Hello ' # Use opentracing's default no-op implementation with contextlib.closing(opentracing.Tracer()) as impl: opentracing.tracer = impl add_spans() #Use LightStep's debug tracer, which logs to the console instead of reporting to LightStep. with contextlib.closing(lightstep.tracer.init_debug_tracer()) as impl: opentracing.tracer = impl add_spans() # Use LightStep's opentracing implementation with contextlib.closing(lightstep_tracer_from_args()) as impl: opentracing.tracer = impl add_spans() print 'World!'