【Sentry使用】自定义transaction

2023-11-11

在使用Sentry时,你会发现有两种颜色的柱形图,一个是紫色的,在上面;一个是灰色的,在下面。这两类柱形图分别代表error和transaction,而在Python脚本环境下,不会自动进行transaction的记录,也就是说只会在出现异常时进行记录,而正常情况不会。
在这里插入图片描述
这时就要了解一下Sentry的transaction创建逻辑

  • 自动
  • 手动

首先是自动
在这里插入图片描述
在使用一些框架的情况下会自动创建,官方给出了这些框架的列表

  • 基于WSGI的web框架,比如Django、Flask、Pyramid、Falcon、Bottle等
  • Celery
  • AIOHTTP web 应用
  • Redis Queue

spans就是在一个transaction中对下列类型操作的记录

  • 使用SQLAlchemy或者Django ORM对数据库进行检索
  • 使用requests或者stdlib进行HTTP请求
  • Spawn方式创建的子进程
  • Redis操作

以下面的一个爬虫transaction为例,可以看到spans记录的有http请求以及db操作,而数据处理的部分则是没有记录,显示为‘Missing instrumentation’
在这里插入图片描述
如何将这些‘Missing instrumentation’变为自定义的呢?

from sentry_sdk import Hub

def process_item(item):
    transaction = Hub.current.scope.transaction
    # omitted code...
    with transaction.start_child(op="http", description="GET /") as span:
        response = my_custom_http_library.request("GET", "/")
        span.set_tag("http.status_code", response.status_code)
        span.set_data("http.foobarsessionid", get_foobar_sessionid())

参考:https://sentry-docs-git-sentry-ruby-40.sentry.dev/platforms/python/performance/#:~:text=op%20and%20description.-,Python,-Copied
如果想在span中创建span

from sentry_sdk import Hub

def process_item(item):
    parent_span = Hub.current.scope.span
    # omitted code...
    with parent_span.start_child(op="http", description="GET /") as span:
        response = my_custom_http_library.request("GET", "/")
        span.set_tag("http.status_code", response.status_code)
        span.set_data("http.foobarsessionid", get_foobar_sessionid())

参考:https://sentry-docs-git-sentry-ruby-40.sentry.dev/platforms/python/performance/#:~:text=tree%20of%20spans%3A-,Python,-Copied

那么如何手动创建transaction呢?
其实,上图中的transaction就是通过手动创建的

from sentry_sdk import start_transaction

while True:
  item = get_from_queue()

  with start_transaction(op="task", name=item.get_transaction_name()):
      # process_item may create more spans internally (see next examples)
      process_item(item)

这种就适合于那种没有使用框架的Python脚本使用

参考:
https://docs.sentry.io/platforms/python/performance/instrumentation/automatic-instrumentation/
https://docs.sentry.io/platforms/python/performance/instrumentation/custom-instrumentation/


根据官方说明
status用来计算failure_rate,而failure_rate表示不成功事务的百分比。 Sentry 将状态不是“ok”、“cancelled”和“unknown”的事务视为失败。
我们看到,所有自定义transaction的状态都是unknown
在这里插入图片描述
如果想将其改为’ok’,可以将status参数设置为’ok’

with start_transaction(op='xxxx', name='xxxx', status='ok') as transaction:
    ...
    ...

在这里插入图片描述
参考:https://develop.sentry.dev/sdk/event-payloads/span/


首先是希望在多进程中使用,根据官方说明写出了如下代码:

# main.py
from sentry_sdk import start_transaction
from multiprocessing import Process
import zhuo
import long

with start_transaction(op='xxxx', name='xxxx', status='ok') as transaction:
    p1 = Process(target=zhuo.main)
    p2 = Process(target=long.main)
    p1.start()
    p2.start()
    p1.join()
    p2.join()
# zhuo.py
import sentry_sdk

transaction = sentry_sdk.Hub.current.scope.transaction

def main():
    with transaction.start_child(op="zhuo"):
        ...
        ...
# long.py
import sentry_sdk

transaction = sentry_sdk.Hub.current.scope.transaction

def main():
    with transaction.start_child(op="long"):
        ...
        ...

但是报错

AttributeError: 'NoneType' object has no attribute 'start_child'

也就是说

transaction = sentry_sdk.Hub.current.scope.transaction

总是为None
所以就将代码改为如下:

# main.py
from sentry_sdk import start_transaction
from multiprocessing import Process
import zhuo
import long

with start_transaction(op='xxxx', name='xxxx', status='ok') as transaction:
    p1 = Process(target=zhuo.main, args=(transaction, ))
    p2 = Process(target=long.main, args=(transaction, ))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
# zhuo.py
import sentry_sdk

def main(transaction: sentry_sdk.tracing.Transaction):
    with transaction.start_child(op="zhuo"):
        ...
        ...
# long.py
import sentry_sdk

transaction = sentry_sdk.Hub.current.scope.transaction

def main(transaction: sentry_sdk.tracing.Transaction):
    with transaction.start_child(op="long"):
        ...
        ...

但这时又报错

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    process.start()
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/process.py", line 121, in start
    self._popen = self._Popen(self)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/context.py", line 284, in _Popen
    return Popen(process_obj)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 32, in __init__
    super().__init__(process_obj)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/popen_fork.py", line 19, in __init__
    self._launch(process_obj)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 47, in _launch
    reduction.dump(process_obj, fp)
  File "/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_thread.RLock' object

原因是transaction无法被pickle序列化,解决思路是将transaction的构建放在目标函数中,这里只传Python自身的数据类型。但问题是transaction无法重新构建,每个进程必须要传入同一个transaction对象,故暂时无法解决。

参考:
https://blog.csdn.net/weixin_43064185/article/details/103213823
https://stackoverflow.com/questions/44144584/typeerror-cant-pickle-thread-lock-objects

多进程不行就改为多线程试试

# main.py
from sentry_sdk import start_transaction
from threading import Thread
import zhuo
import long

with start_transaction(op='xxxx', name='xxxx', status='ok') as transaction:
    p1 = Thread(target=zhuo.main, args=(transaction, ))
    p2 = Thread(target=long.main, args=(transaction, ))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
# zhuo.py
import sentry_sdk

def main(transaction: sentry_sdk.tracing.Transaction):
    with transaction.start_child(op="zhuo"):
        ...
        ...
# long.py
import sentry_sdk

transaction = sentry_sdk.Hub.current.scope.transaction

def main(transaction: sentry_sdk.tracing.Transaction):
    with transaction.start_child(op="long"):
        ...
        ...

一切正常了

transaction = sentry_sdk.Hub.current.scope.transaction

依旧为None
可以看到zhuo与long中的所有http请求以及数据库操作均被记录下来
所以这种方式仅适用于调试阶段,如果数据量过大,可能造成sentry服务器崩溃
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【Sentry使用】自定义transaction 的相关文章

  • Python在postgresql表中查找带有单引号符号的字符串

    我需要从 psql 表中查找包含多个单引号的字符串 我当前的解决方案是将单引号替换为双单引号 如下所示 sql query f SELECT exists SELECT 1 FROM table name WHERE my column m
  • Jupyter Notebooks 不显示进度条

    我正在尝试在 Jupyter 笔记本中显示进度条 这是一台新电脑 我通常做的事情似乎不起作用 from tqdm import tqdm notebook example iter 1 2 3 4 5 for rec in tqdm not
  • TF map_fn 或 while_loop 用于不同形状的张量列表

    我想处理不同形状的张量序列 列表 并输出另一个张量列表 考虑每个时间戳上具有不同隐藏状态大小的 RNN 就像是 输入 tf ones 1 2 2 tf ones 2 2 3 tf ones 3 2 1 输出 tf zeros 1 2 4 t
  • 根据开始列和结束列扩展数据框(速度)

    我有一个pandas DataFrame含有start and end列 加上几个附加列 我想将此数据框扩展为一个时间序列 从start值并结束于end值 但复制我的其他专栏 到目前为止 我想出了以下内容 import pandas as
  • 更改 Altair 中的构面标题位置?

    如何将方面标题 在本例中为年份 移动到每个图的上方 默认值似乎位于图表的一侧 这可以轻易改变吗 import altair as alt from vega datasets import data df data seattle weat
  • 登录网站并使用 python 请求下载文件

    我有一个带有 HTML 表单的网站 登录后 它会将我带到 start php 站点 然后将我重定向到overview php 我想从该服务器下载文件 当我单击 ZIP 文件的下载链接时 链接后面的地址是 getimage php path
  • 如何在 Python 3 中循环遍历集合,同时从集合中删除项目

    这是我的情况 我有一个list set 哪个并不重要 movieplayer我想调用的对象 preload 功能开启 该预加载函数可以立即返回 但希望将来返回一点 我想存储这个电影播放器 集合 表明它们尚未预加载 然后循环它们 调用prel
  • 如何将 self 传递给装饰器?

    我该如何通过self key下面进入装饰器 class CacheMix object def init self args kwargs super CacheMix self init args kwargs key func Cons
  • 更改 python tkinter canvas 中的线坐标

    我画了一条线tkinter Canvas现在我想移动一端 这可能吗 例如和itemconfig import tkinter tk tkinter Tk canvas tkinter Canvas tk canvas pack line c
  • python 中的 Johansen 协整检验

    我找不到任何有关在处理统计和时间序列分析 pandas 和 statsmodel 的 Python 模块中执行 Johansen 协整检验的功能的参考 有谁知道是否有一些代码可以执行时间序列之间的协整测试 现在 这已在 Python 的 s
  • 使用 scipy curve_fit 拟合噪声指数的建议?

    我正在尝试拟合通常按以下方式建模的数据 def fit eq x a b c d e return a 1 np exp x b c np exp x d e x np arange 0 100 0 001 y fit eq x 1 1 1
  • Apache Spark 中的高效字符串匹配

    我使用 OCR 工具从屏幕截图中提取文本 每个大约 1 5 句话 然而 当手动验证提取的文本时 我注意到时不时会出现一些错误 鉴于文本 你好 我真的很喜欢 Spark 我注意到 1 像 I 和 l 这样的字母被 替换 2 表情符号未被正确提
  • 为什么我无法在 Mac OS X Terminal.app 上的 Python 解释器中显示 unicode 字符?

    如果我尝试粘贴 unicode 字符 例如中间的点 在我的 python 解释器中它什么也不做 我在 Mac OS X 上使用 Terminal app 当我只是在 bash 中时 我没有遇到任何问题 但在解释器中 python Pytho
  • `list()` 被认为是一个函数吗?

    list显然是内置类型 https docs python org 3 library stdtypes html list在Python中 我看到底下有一条评论this https stackoverflow com a 53645813
  • 将文本注释到轴并对齐为圆

    我正在尝试在轴上绘制文本并将该文本与圆对齐 更准确地说 有一些具有不同坐标 x y 的点位于该圆内 并使用以下命令创建 ax scatter x y s 100 我想用圆圈连接并标记每个点 Cnameb 文本的坐标由 xp yp 定义 因此
  • Python]将两个文本文件合并为一个(逐行)[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我是蟒蛇新手 我想做的是将文件 a 和文件 b 逐行合并到一个文件中 例如 text file a a n b n c text fi
  • 在 virtualenvwrapper 中激活环境

    我安装了virtualenv and virtualenvwrapper用这个命令我创建了一个环境 mkvirtualenv cv 它有效 创建后我就处于新环境中 现在我重新启动了我的电脑 我想activate又是那个环境 但是怎么样 我使
  • 如何为所有用户安装 Anaconda python?

    Anaconda python 发行版 https store continuum io cshop anaconda 非常方便地部署科学计算环境 SCE 并根据需要切换python版本 默认情况下 安装会将 python 定位到 anac
  • python sklearn中的fit方法

    我问自己关于 sklearn 中拟合方法的各种问题 问题1 当我这样做时 from sklearn decomposition import TruncatedSVD model TruncatedSVD svd 1 model fit X
  • 缓存 Flask-登录 user_loader

    我有这个 login manager user loader def load user id None return User query get id 在我引入 Flask Principal 之前它运行得很好 identity loa

随机推荐

  • CloudOS:物联网开发平台,云上开发,边端交付

    文章目录 一 CloudOS概述 二 CloudOS主要功能 1 云上开发 2 边端交付 3 数据管理 4 安全保障 三 CloudOS应用场景 1 智能家居 2 智慧城市 3 工业物联网 四 总结 欢迎来到云计算技术应用专栏 CloudO
  • 工作中如何做好技术积累(摘自美团点评技术团队博客)

    引言 古人云 活到老 学到老 互联网算是最辛苦的行业之一 加班 对工程师来说已是 家常便饭 同时互联网技术又日新月异 很多工程师都疲于应付 叫苦不堪 以至于长期以来流传一个很广的误解 35岁是程序员工作的终点 如何在繁忙的工作中做好技术积累
  • 由于设备驱动程序的前一个实例仍在内存中,Windows 无法加载这个硬件的设备驱动

    感谢这位 sizzg7796 网友
  • 【Jenkins】部署vue项目(多种方式部署)

    文章目录 Jenkins部署vue项目 先安装node js 上传到linux并解压 配置Jenkins 环境变量 jenkins 创建任务 部署方式 第一种 npm run build 打包的形式 执行脚本 build Steps 第二种
  • Detr代码解读(一)数据加载

    文章目录 导读 数据加载 dataset train 数据源文件不存在报错解决 CocoDetection 采样 数据处理 处理 target 处理 img 收集策略 collate fn batch 导读 源码 Detr Detr用的数据
  • 深入理解React Hooks与闭包:提升你的React开发技能

    深入理解React Hooks与闭包 提升你的React开发技能 深入理解React Hooks与闭包 提升你的React开发技能 深入理解React Hooks与闭包 提升你的React开发技能 前言 1 React Hooks 简介 2
  • PID双环控制(速度环和位置环)

    PID双环的控制过程 PID双环控制的前期准备 代码实现步骤 效果图 位置环做为外环 速度环作为内环 可以看到外环的输出值作为内环的目标值 外环计算一次pid 我们根据pid公式可以知道 当离位置目标越来越近时 第一个误差 外环误差 就越来
  • python输出结果去掉引号_从二维数组python中删除引号

    我目前正在尝试执行对具有大指数的幂进行赋值的代码 而不对其进行计算 而是对其进行记录 我有一个包含1000行的file 每行包含两个由逗号分隔的iteger 我被困在试图从数组中删除引号的位置 我尝试了许多方法 但都无济于事 这是我的代码
  • 转---30 分钟学会 Flex 布局

    正文从这开始 Flex 基本概念 在 flex 容器中默认存在两条轴 水平主轴 main axis 和垂直的交叉轴 cross axis 这是默认的设置 当然你可以通过修改使垂直方向变为主轴 水平方向变为交叉轴 这个我们后面再说 在容器中的
  • 使用three.js加载obj+mtl模型

    已经有比较好的博客介绍如何加载模型 使用three js加载obj mtl模型完整案例 有一点小问题 会导致模型加载不成功 需要修改两处地方 1 将 Detector js 替换为 WebGL js 根据Three js中Detector
  • 自动登录远程服务器脚本,iTerm2使用脚本自动登录远程服务器

    在iTerm2下ssh不能自动登录 不自动登录每次输入命令太麻烦了 这里介绍一个采取expect脚本的方式实现iTerm2下ssh自动登录 新建一个expect脚本 login exp usr bin expect if llength a
  • 从无监督构建词库看「最小熵原理」,套路是如何炼成的

    作者丨苏剑林 单位丨广州火焰信息科技有限公司 研究方向丨NLP 神经网络 个人主页丨kexue fm 在深度学习等端到端方案已经逐步席卷 NLP 的今天 你是否还愿意去思考自然语言背后的基本原理 我们常说 文本挖掘 你真的感受到了 挖掘 的
  • Unity iOS打开AppStore评星页面,浅谈Application.OpenURL()方法。

    http fairwoodgame com blog p 38 Unity iOS打开AppStore评星页面 浅谈Application OpenURL 方法 Posted in Unity on August 6 2013Comment
  • 8、工厂方法

    文章目录 概念 demo 概念 定义一个创建对象的接口 让其子类自己决定实例化哪一个工厂类 工厂模式使其创建过程延迟到子类进行 demo package com cn go designpattern public class Factor
  • 同步、异步、阻塞、非阻塞的理解

    同步 异步 阻塞 非阻塞的理解 有关这四个概念总会混淆 前几天特意查了下 简单理解了下这四个概念 若理解的不对 希望大家指正 一 同步异步 同步是调用者发出请求后 一直等待被调用者响应 如果被调用者没有响应那会一直不返回 以买书为例 如下
  • counterfactual generation network——因果推断用于提高分类器鲁棒性

    因果推断本是一个小众方向 但是感觉近几年突然火了起来 本文便是2021年发表于ICLR的一篇将因果推断用于提高图像分类的文章 本文出发点 先说一下本文针对的问题 我们知道图像分类任务就是将输入网络的图像尽量映射成我们想要的输出结果 通常是一
  • 2021江西省icpc(A,B,D,F,G,H,J,K,L)

    K Many Littles Make a Mickle 签到题 任意门 先从最简单的签到题开始吧 include
  • IPIDEA的使用方式

    文章目录 一 平台介绍 1 前言 2 简单介绍 3 适用场景 4 特色功能 二 获取代理ip池 1 注册信息 2 获取代理API 3 获取代理信息并检测代理可用性 三 代理爬取数据 1 编写功能代码 2 插入到代理代码 四 使用感受 一 平
  • Mac OS X 上干净卸载软件

    英文参考文章地址 http www cultofmac com 90060 how to completely uninstall software under mac os x macrx 在Mac OS X上卸载软件一般都很简单 在 应
  • 【Sentry使用】自定义transaction

    在使用Sentry时 你会发现有两种颜色的柱形图 一个是紫色的 在上面 一个是灰色的 在下面 这两类柱形图分别代表error和transaction 而在Python脚本环境下 不会自动进行transaction的记录 也就是说只会在出现异