Scopes and multithreading in python

How do I make tags and breadcrumbs captured by events sent from spawned threads?
I have some information that I’d like all events to be sent with, such as the entrypoint cmdline used to start my program, it’s version (not to be confused with release), and other process-wide context data. It appears that set_extra,set_tag,add_breadcrumb are all linked to the current thread (MainThread), but aren’t inherited by subthreads.

Hi @koreno

You would need to get Hub.current in the spawning thread and pass it to your child thread. In that thread, wrap your code with:

with Hub(hub_passed):
    # thread code goes here

Automatic inheritance is unfortunately not possible unless we monkeypatch threading.

1 Like

After digging around some I found sentry_sdk.hub.GLOBAL_HUB, which I configure its scope and affect the entire session:

    with sentry_sdk.hub.GLOBAL_HUB.configure_scope() as scope:
        scope.set_tag("cmd", cmd)

That’s the same hub as Hub.main. If you are calling the regular configure_scope() on the main thread it will have the same effect.

It doesn’t seem so. The end result was different - threads did not contain the scope configuration set in the MainThread.
It seems that when threads look for their thread-local hub, they copy this GLOBAL_HUB. The MainThread probably copies it as well, so modifying it does not modify the other threads.

Here is the implementation of Hub.main:

Here is where Hub.current is set to GLOBAL_HUB in the thread that imported the SDK (which is likely the main thread):

if you see different behavior please file a bug