elastic / elastic/apm-agent-python

Support for setting the execution context after import time to support late gevent patching

未关闭
#894 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
agent-python feature
主要语言
Python
星标
431
派生
239
平均合并
5 天 10 小时
30 天内合并 PR
7

描述

**Is your feature request related to a problem? Please describe.**
I'm working with a legacy codebase that imports some code, forks and does gevent monkey patching, then imports a bunch more code. I'm running into an issue where `elasticapm.traces.execution_context` is initialized at import time during the first phase, using the not-monkeypatched `threading.local` / `contextvars`, which causes transactions / spans to be linked to the wrong requests.

**Describe the solution you'd like**
Since fixing my codebase to not import the logging code is rather involved, I am looking for a safe way to either re-initialize the current execution context or assign it to a newly constructed instance. Ideally, I would be able to do something like

```py
set_execution_context(ThreadLocalContext())
```

after I know gevent has done its patching. This would also open the door for using custom execution context implementations, if someone ever wanted to do that.

This seems like it would be a bit tricky to implement in the library as it is now, since there is a lot of
```py
from elasticapm.traces import execution_context
```
which AFAIK makes it impractical to do something like `elasticapm.traces.execution_context = Blah()` due to the multiple names [thing](https://docs.python.org/3/library/unittest.mock.html#where-to-patch).

**Describe alternatives you've considered**
I've converted our setup code to use only local imports for elasticapm (in functions executed after I know gevent has finished patching), which works okay. It's a little fragile, though - if anyone ever imports elasticapm without the proper guards things could break again.

I think this might be specific to our codebase - we should really be patching gevent before we import things anyway. Feel free to close if this doesn't seem worth the effort, since I have a pretty solid work-around. Love the library and great work. 😄

贡献指南

打开贡献指南

调研方向

首先追踪 elasticapm.traces.execution_context 的初始化方式,以及其中导入的名称在整个包中的使用方式。研究一种在 gevent 打补丁后安全替换或重新初始化该上下文的方法,然后验证 transactions 和 spans 使用的是新上下文,同时不破坏现有的 imports。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
observability-sre
Issue 类型
功能
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。