首先说一下心得:一定要看官方文档,绝大部分的案例及问题官方文档都会有说明
之前用sentry+flask,把失败的响应都传到sentry上。但发现,信息中缺少两个至关重要的定位信息’appId’和’entryId’,我希望它能出现在tags中
最开始是想通过before_send方法在send前对event进行一些处理,比如添加tag。
import sentry_sdk
def before_send(event, hint):
event['tag'] = {'appId':'xxxxx', 'entryId':'xxxxx'}
return event
sentry_sdk.init(
dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
before_send=before_send,
)
经过验证,像上面那样通过给event添加tag键,确实能在tags中设置自定义tag。但问题来了,我的每个请求appId和eventId都不同,那该如何针对每个请求设置不同的event呢?
如果用上面的方式只能实现全局唯一的tag设置,至少我还没找到方法,所以此路不通。
搜索了很久,发现使用local scope可以实现
关于scope的概念,你可以把它看作包含有额外信息的字典,在发送最终信息前,scope会和event融合,发送给sentry服务器,子scope继承父scope的所有信息,而对子scope的修改不会影响到父scope。有没有觉得很像继承实现实例化对象的概念,这样我们就可以针对每个请求,生成一个子scope,再向其中添加tag就好了。实现方式就是在原来每条请求进行处理的函数内,将代码用with-scope包裹,再在包裹的代码开头进行set_tag。
from sentry_sdk import push_scope
def process():
with push_scope() as scope:
scope.set_tag("appId", "xxxxx")
scope.set_tag("entryId", "xxxxx")
...
注意:如果process()函数内部存在子进程或子线程,则该scope无法覆盖子进程或子线程的代码,即无法添加自定义tag
需要在子进程或子线程中也使用with-scope
import threading
from sentry_sdk import push_scope
def process():
with push_scope() as scope:
scope.set_tag("appId", "xxxxx")
scope.set_tag("entryId", "xxxxx")
...
threading.Thread(target=asyn, args=()).start()
def asyn():
with push_scope() as scope:
scope.set_tag("appId", "xxxxx")
scope.set_tag("entryId", "xxxxx")
...
最后的效果如下图,tags中出现我们希望的tag了
参考:https://docs.sentry.io/platforms/python/guides/logging/enriching-events/scopes/#local-scopes
2021-08-21 更新
在connexion中使用with-scope时,如果不使用capture_exception,则在sentry中无法显示自定义tag,示例代码如下所示:
from sentry_sdk import push_scope, capture_exception
def postjdyv1(body=None):
with push_scope() as scope:
try:
if connexion.request.is_json:
payload = connexion.request.get_json()
if payload['op'] != 'data_test':
appId = payload['data']['appId']
entryId = payload['data']['entryId']
dataId = payload['data']['_id']
# 设置sentry tag
scope.set_tag('appId', appId)
scope.set_tag('entryId', entryId)
scope.set_tag('dataId', dataId)
res = postjdyv1_module.post_jdyv1(connexion.request)
return res
else:
raise
except Exception as e:
capture_exception(e)
raise e