Skip to content

Fix thread name CallsiteParameterAdder in async methods (issue #710)#805

Open
BlocksecPHD wants to merge 2 commits intohynek:mainfrom
BlocksecPHD:fix-async-thread-info-710
Open

Fix thread name CallsiteParameterAdder in async methods (issue #710)#805
BlocksecPHD wants to merge 2 commits intohynek:mainfrom
BlocksecPHD:fix-async-thread-info-710

Conversation

@BlocksecPHD
Copy link
Copy Markdown

Problem

When using async logging methods (.ainfo(), etc.), the CallsiteParameterAdder processor was collecting thread information from the executor thread pool instead of the caller's thread. This caused thread_name to show 'asyncio_0' instead of the actual caller thread like 'MainThread'.

Solution

This fix captures thread info (thread_id and thread_name) before passing control to the executor thread, storing it in a contextvar (_ASYNC_CALLING_THREAD) that is copied along with the calling stack frame. The processor then uses this captured thread info when available.

Changes

  1. contextvars.py: Added _ASYNC_CALLING_THREAD contextvar to store captured thread info
  2. _native.py: Updated async methods to capture thread info before executor
  3. stdlib.py: Updated async methods in both BoundLogger and AsyncBoundLogger to capture thread info
  4. processors.py: Updated _get_callsite_thread and _get_callsite_thread_name to use captured info from contextvar
  5. tests: Added tests to verify thread info is correctly captured in async context

Testing

All tests pass:

  • Native async tests
  • Stdlib async tests
  • AsyncBoundLogger tests
  • Existing processor tests

Example Output

Before fix:

thread_name=asyncio_0  # Wrong - executor thread

After fix:

thread_name=MainThread  # Correct - caller's thread

Fixes #710

Funan Zhou and others added 2 commits April 10, 2026 06:16
)

When using async logging methods (.ainfo(), etc.), the CallsiteParameterAdder
processor was collecting thread information from the executor thread pool
instead of the caller's thread, causing thread_name to show 'asyncio_0'
instead of the actual caller thread like 'MainThread'.

This fix captures thread info (thread_id and thread_name) before passing
control to the executor thread, storing it in a contextvar that is copied
along with the calling stack frame. The processor then uses this captured
thread info when available.

Changes:
- Add _ASYNC_CALLING_THREAD contextvar in contextvars.py
- Update async methods in _native.py to capture thread info
- Update async methods in stdlib.py (BoundLogger and AsyncBoundLogger)
- Update CallsiteParameterAdder to use captured thread info from contextvar
- Add tests for async thread info capture

Fixes hynek#710
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thread name CallsiteParameterAdder parameter doesn't work in async methods

1 participant