You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用Sentry-SDK及外部工具,通过DSN向Sentry发送事件?

仅用DSN向Sentry发送事件的无依赖Python实现

核心思路是直接调用Sentry的事件上报API——DSN本身已经包含了所有必要的认证和地址信息,无需SDK或外部工具。

步骤说明

  1. 解析DSN:从你的DSN中提取协议、公钥、密钥、主机地址和项目ID
  2. 构造事件Payload:按照Sentry的事件格式要求生成JSON数据
  3. 发送POST请求:用Python标准库urllib.request发送请求,带上认证头部

完整代码示例

import urllib.request
import json
import sys
import uuid
from urllib.parse import urlparse

def parse_sentry_dsn(dsn):
    parsed = urlparse(dsn)
    return {
        "protocol": parsed.scheme,
        "public_key": parsed.username,
        "secret_key": parsed.password,
        "host": parsed.netloc,
        "project_id": parsed.path.lstrip('/')
    }

def send_sentry_event(dsn, event_data):
    dsn_parts = parse_sentry_dsn(dsn)
    api_url = f"{dsn_parts['protocol']}://{dsn_parts['host']}/api/{dsn_parts['project_id']}/store/"
    
    headers = {
        "Content-Type": "application/json",
        "X-Sentry-Auth": (
            f"Sentry sentry_version=7,"
            f"sentry_key={dsn_parts['public_key']},"
            f"sentry_secret={dsn_parts['secret_key']}"
        )
    }
    
    try:
        req = urllib.request.Request(api_url, data=json.dumps(event_data).encode('utf-8'), headers=headers)
        with urllib.request.urlopen(req) as resp:
            print(f"事件发送成功,状态码: {resp.getcode()}")
            return resp.getcode()
    except Exception as e:
        print(f"发送失败: {str(e)}", file=sys.stderr)
        return None

if __name__ == "__main__":
    # 替换成你的Sentry DSN
    SENTRY_DSN = "https://your-public-key@your-sentry-instance.com/your-project-id"
    
    # 生成唯一事件ID(32位十六进制)
    def generate_event_id():
        return uuid.uuid4().hex
    
    # 构造错误事件
    error_event = {
        "event_id": generate_event_id(),
        "timestamp": "2024-05-20T14:30:00Z",
        "message": "脚本执行出错",
        "level": "error",
        "platform": "python",
        "exception": {
            "values": [
                {
                    "type": "FileNotFoundError",
                    "value": "找不到指定配置文件",
                    "stacktrace": {
                        "frames": [
                            {
                                "filename": "my_script.py",
                                "function": "load_config",
                                "lineno": 15,
                                "colno": 8
                            }
                        ]
                    }
                }
            ]
        }
    }
    
    # 构造信息事件
    info_event = {
        "event_id": generate_event_id(),
        "timestamp": "2024-05-20T14:30:05Z",
        "message": "脚本执行完成",
        "level": "info",
        "platform": "python",
        "extra": {
            "execution_time": "2.5s",
            "processed_items": 100
        }
    }
    
    # 发送两个事件
    send_sentry_event(SENTRY_DSN, error_event)
    send_sentry_event(SENTRY_DSN, info_event)

关键注意点

  • event_id必须是32位十六进制字符串,用uuid.uuid4().hex生成最方便(uuid是Python标准库)
  • 时间戳需遵循ISO 8601格式(如YYYY-MM-DDTHH:MM:SSZ)
  • 事件Payload可以根据需求扩展,比如添加user字段记录用户信息、contexts字段记录设备/环境信息
  • 全程仅使用Python标准库,无任何外部依赖

内容的提问来源于stack exchange,提问作者Archirk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:50:21