Skip to content

doc(python): Add code sample for hub propagation #1560

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 19, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,53 @@ See [_Logging_]({% link _documentation/platforms/python/logging.md %})
Reports crashing threads.

It also accepts an option `propagate_hub` that changes the way clients are transferred between threads, and transfers scope data (such as tags) from the parent thread to the child thread. This option is currently disabled (`False`) by default, but this will likely change in the future.

Next are two code samples that demonstrate what boilerplate you would have to write without `propagate_hub`. This boilerplate is still sometimes necessary if you want to propagate context data into a thread pool, for example.

### Manual propagation

```python
import threading
from sentry_sdk import Hub, init, configure_scope, capture_message

init(...)

with configure_scope() as scope:
scope.set_tag("mydata", 42)

def run(thread_hub):
with thread_hub:
capture_message("hi") # event will have `mydata` tag attached

# We take all context data (the tags map and even the entire client
# configuration), and pass it as explicit variable
# into the thread.
thread_hub = Hub(Hub.current)

tr = threading.Thread(target=run, args=[thread_hub])
tr.start()
tr.join()
```

### Example B: Automatic propagation
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we often use headings inside code blocks? Or should the previous block and and a new one begin around this heading?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed... wanted to share imports but it's cleaner this way


```python
import threading

from sentry_sdk import Hub, init, configure_scope, capture_message
from sentry_sdk.integrations.threading import ThreadingIntegration

init(..., integrations=[ThreadingIntegration(propagate_hub=True)])

with configure_scope() as scope:
scope.set_tag("mydata", 42)

def run():
capture_message("hi") # event will have `mydata` tag attached

# The threading integration hooks into the stdlib to automatically pass
# existing context data when a `Thread` is instantiated.
tr = threading.Thread(target=run)
tr.start()
tr.join()
```