Skip to content

Commit f0d18bd

Browse files
authored
doc(python): Add code sample for hub propagation (#1560)
* doc(python): Add code sample for hub propagation * split up codeblocks
1 parent 2f5fe51 commit f0d18bd

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/collections/_documentation/platforms/python/default-integrations.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,53 @@ See [_Logging_]({% link _documentation/platforms/python/logging.md %})
7878
Reports crashing threads.
7979

8080
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.
81+
82+
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.
83+
84+
### Manual propagation
85+
86+
```python
87+
import threading
88+
from sentry_sdk import Hub, init, configure_scope, capture_message
89+
90+
init(...)
91+
92+
with configure_scope() as scope:
93+
scope.set_tag("mydata", 42)
94+
95+
def run(thread_hub):
96+
with thread_hub:
97+
capture_message("hi") # event will have `mydata` tag attached
98+
99+
# We take all context data (the tags map and even the entire client
100+
# configuration), and pass it as explicit variable
101+
# into the thread.
102+
thread_hub = Hub(Hub.current)
103+
104+
tr = threading.Thread(target=run, args=[thread_hub])
105+
tr.start()
106+
tr.join()
107+
```
108+
109+
### Example B: Automatic propagation
110+
111+
```python
112+
import threading
113+
114+
from sentry_sdk import Hub, init, configure_scope, capture_message
115+
from sentry_sdk.integrations.threading import ThreadingIntegration
116+
117+
init(..., integrations=[ThreadingIntegration(propagate_hub=True)])
118+
119+
with configure_scope() as scope:
120+
scope.set_tag("mydata", 42)
121+
122+
def run():
123+
capture_message("hi") # event will have `mydata` tag attached
124+
125+
# The threading integration hooks into the stdlib to automatically pass
126+
# existing context data when a `Thread` is instantiated.
127+
tr = threading.Thread(target=run)
128+
tr.start()
129+
tr.join()
130+
```

0 commit comments

Comments
 (0)