Skip to content

Commit

Permalink
Integrate tracer with context (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
reyang authored Aug 20, 2019
1 parent 17afba5 commit 20011c5
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 24 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@

The Python [OpenTelemetry](https://opentelemetry.io/) client.

## Installation

## Usage
```python
from opentelemetry import trace
from opentelemetry.context import Context
from opentelemetry.sdk.trace import Tracer

trace.set_preferred_tracer_implementation(lambda T: Tracer())
tracer = trace.tracer()
with tracer.start_span('foo'):
print(Context)
with tracer.start_span('bar'):
print(Context)
with tracer.start_span('baz'):
print(Context)
print(Context)
print(Context)
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md)
14 changes: 9 additions & 5 deletions opentelemetry-api/src/opentelemetry/context/base_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,9 @@ def register_slot(
:returns: The registered slot.
"""
with cls._lock:
if name in cls._slots:
raise ValueError('slot {} already registered'.format(name))
slot = cls.Slot(name, default)
cls._slots[name] = slot
return slot
if name not in cls._slots:
cls._slots[name] = cls.Slot(name, default)
return cls._slots[name]

def apply(self, snapshot: typing.Dict[str, 'object']) -> None:
"""Set the current context from a given snapshot dictionary"""
Expand Down Expand Up @@ -97,6 +95,12 @@ def __setattr__(self, name: str, value: 'object') -> None:
slot = self._slots[name]
slot.set(value)

def __getitem__(self, name: str) -> 'object':
return self.__getattr__(name)

def __setitem__(self, name: str, value: 'object') -> None:
self.__setattr__(name, value)

def with_current_context(
self,
func: typing.Callable[..., 'object'],
Expand Down
25 changes: 11 additions & 14 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
from collections import deque
from collections import namedtuple
from contextlib import contextmanager
import contextvars
import random
import threading
import typing

from opentelemetry import trace as trace_api
from opentelemetry import types
from opentelemetry.context import Context
from opentelemetry.sdk import util

try:
Expand All @@ -35,9 +35,6 @@
from collections import MutableMapping
from collections import Sequence


_CURRENT_SPAN_CV = contextvars.ContextVar('current_span', default=None)

MAX_NUM_ATTRIBUTES = 32
MAX_NUM_EVENTS = 128
MAX_NUM_LINKS = 32
Expand Down Expand Up @@ -287,21 +284,20 @@ class Tracer(trace_api.Tracer):
"""See `opentelemetry.trace.Tracer`.
Args:
cv: The context variable that holds the current span.
name: The name of the tracer.
"""

def __init__(self,
cv: 'contextvars.ContextVar' = _CURRENT_SPAN_CV
name: str = ''
) -> None:
self._cv = cv
try:
self._cv.get()
except LookupError:
self._cv.set(None)
slot_name = 'current_span'
if name:
slot_name = '{}.current_span'.format(name)
self._current_span_slot = Context.register_slot(slot_name)

def get_current_span(self):
"""See `opentelemetry.trace.Tracer.get_current_span`."""
return self._cv.get()
return self._current_span_slot.get()

@contextmanager
def start_span(self,
Expand Down Expand Up @@ -341,11 +337,12 @@ def create_span(self,
def use_span(self, span: 'Span') -> typing.Iterator['Span']:
"""See `opentelemetry.trace.Tracer.use_span`."""
span.start()
token = self._cv.set(span)
span_snapshot = self._current_span_slot.get()
self._current_span_slot.set(span)
try:
yield span
finally:
self._cv.reset(token)
self._current_span_slot.set(span_snapshot)
span.end()


Expand Down
7 changes: 2 additions & 5 deletions opentelemetry-sdk/tests/trace/test_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

from unittest import mock
import contextvars
import unittest

from opentelemetry import trace as trace_api
Expand All @@ -30,8 +29,7 @@ def test_extends_api(self):
class TestSpanCreation(unittest.TestCase):

def test_start_span_implicit(self):
context = contextvars.ContextVar('test_start_span_implicit')
tracer = trace.Tracer(context)
tracer = trace.Tracer('test_start_span_implicit')

self.assertIsNone(tracer.get_current_span())

Expand Down Expand Up @@ -69,8 +67,7 @@ def test_start_span_implicit(self):
self.assertIsNotNone(root.end_time)

def test_start_span_explicit(self):
context = contextvars.ContextVar('test_start_span_explicit')
tracer = trace.Tracer(context)
tracer = trace.Tracer('test_start_span_explicit')

other_parent = trace_api.SpanContext(
trace_id=0x000000000000000000000000deadbeef,
Expand Down

0 comments on commit 20011c5

Please sign in to comment.