【Sentry使用】使用local scope实现动态添加自定义tag

44 篇文章 0 订阅
9 篇文章 1 订阅

首先说一下心得:一定要看官方文档,绝大部分的案例及问题官方文档都会有说明


之前用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值