sentry-setup-metrics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSetup Sentry Metrics
配置Sentry Metrics
This skill helps configure Sentry's custom metrics feature to track counters, gauges, and distributions across your applications.
本指南帮助你配置Sentry的自定义指标功能,以在应用中追踪计数器、仪表盘和分布统计数据。
When to Use This Skill
适用场景
Invoke this skill when:
- User asks to "setup Sentry metrics" or "add custom metrics"
- User wants to "track metrics in Sentry"
- User requests "counters", "gauges", or "distributions" with Sentry
- User mentions they want to track business KPIs or application health
- User asks about or
Sentry.metricssentry_sdk.metrics - User wants to instrument performance metrics
在以下场景中使用本指南:
- 用户要求“配置Sentry指标”或“添加自定义指标”
- 用户希望“在Sentry中追踪指标”
- 用户需要使用Sentry实现“计数器”“仪表盘”或“分布统计”
- 用户提及要追踪业务KPI或应用健康状况
- 用户询问或
Sentry.metrics相关内容sentry_sdk.metrics - 用户希望为性能指标做埋点
Platform Support
平台支持
Supported Platforms:
- JavaScript/TypeScript (SDK 10.25.0+): Next.js, React, Node.js, Browser
- Python (SDK 2.44.0+): Django, Flask, FastAPI, general Python
Note: Ruby does not currently have dedicated metrics support in the Sentry SDK.
支持的平台:
- JavaScript/TypeScript(SDK 10.25.0+):Next.js、React、Node.js、浏览器
- Python(SDK 2.44.0+):Django、Flask、FastAPI、通用Python项目
注意: Ruby目前在Sentry SDK中没有专门的指标支持。
Metric Types Overview
指标类型概述
Before setup, explain the three metric types to the user:
| Type | Purpose | Use Cases | Aggregations |
|---|---|---|---|
| Counter | Track cumulative occurrences | Button clicks, API calls, errors | sum, per_second, per_minute |
| Gauge | Point-in-time snapshots | Queue depth, memory usage, connections | min, max, avg |
| Distribution | Statistical analysis of values | Response times, cart amounts, query duration | p50, p75, p95, p99, avg, min, max |
开始配置前,先向用户说明三种指标类型:
| 类型 | 用途 | 适用场景 | 聚合方式 |
|---|---|---|---|
| Counter(计数器) | 追踪累计发生次数 | 按钮点击、API调用、错误次数 | sum、per_second、per_minute |
| Gauge(仪表盘) | 记录某一时刻的快照值 | 队列深度、内存使用量、连接数 | min、max、avg |
| Distribution(分布统计) | 对数值进行统计分析 | 响应时间、购物车金额、查询耗时 | p50、p75、p95、p99、avg、min、max |
Platform Detection
平台检测
JavaScript/TypeScript Detection
JavaScript/TypeScript检测
Check for these files:
- - Read to identify framework and Sentry SDK version
package.json - Look for ,
@sentry/nextjs,@sentry/react,@sentry/node@sentry/browser - Check if SDK version is 10.25.0+ (required for metrics)
检查以下文件:
- - 读取以识别框架和Sentry SDK版本
package.json - 查找、
@sentry/nextjs、@sentry/react、@sentry/node依赖@sentry/browser - 确认SDK版本为10.25.0+(指标功能的最低要求)
Python Detection
Python检测
Check for:
- ,
requirements.txt,pyproject.toml, orsetup.pyPipfile - Look for version 2.44.0+ (required for metrics)
sentry-sdk
检查以下文件:
- 、
requirements.txt、pyproject.toml或setup.pyPipfile - 确认版本为2.44.0+(指标功能的最低要求)
sentry-sdk
Required Information
需要收集的信息
Ask the user:
I'll help you set up Sentry Metrics. First, let me check your project setup.
After detecting the platform:
1. **What metrics do you want to track?**
- Counters: Event counts (clicks, API calls, errors)
- Gauges: Point-in-time values (queue depth, memory)
- Distributions: Value analysis (response times, amounts)
2. **Do you need metric filtering?**
- Yes: Configure beforeSendMetric to filter/modify metrics
- No: Send all metrics as-is向用户询问:
我将帮你配置Sentry Metrics。首先让我确认你的项目配置情况。
检测到平台后:
1. **你想要追踪哪些类型的指标?**
- 计数器:事件次数(点击、API调用、错误)
- 仪表盘:瞬时值(队列深度、内存)
- 分布统计:数值分析(响应时间、金额)
2. **是否需要指标过滤?**
- 是:配置beforeSendMetric以过滤/修改指标
- 否:直接发送所有指标JavaScript/TypeScript Configuration
JavaScript/TypeScript配置
Minimum SDK Version
最低SDK版本
- All JS platforms:
10.25.0+
- 所有JS平台:
10.25.0+
Step 1: Verify SDK Version
步骤1:验证SDK版本
bash
grep -E '"@sentry/(nextjs|react|node|browser)"' package.jsonIf version is below 10.25.0, inform user to upgrade:
bash
npm install @sentry/nextjs@latest # or appropriate packagebash
grep -E '"@sentry/(nextjs|react|node|browser)"' package.json如果版本低于10.25.0,告知用户升级:
bash
npm install @sentry/nextjs@latest # 或对应平台的包Step 2: Verify Metrics Are Enabled
步骤2:验证指标功能已启用
Metrics are enabled by default in SDK 10.25.0+. No changes to are required unless user wants to disable or filter.
Sentry.init()Locate init files:
- Next.js: ,
instrumentation-client.ts,sentry.server.config.tssentry.edge.config.ts - React: ,
src/index.tsx, or dedicated sentry config filesrc/main.tsx - Node.js: Entry point file or dedicated sentry config
- Browser: Entry point or config file
Optional: Explicitly enable (not required):
javascript
import * as Sentry from "@sentry/nextjs"; // or @sentry/react, @sentry/node
Sentry.init({
dsn: "YOUR_DSN_HERE",
// Metrics enabled by default, but can be explicit
enableMetrics: true,
// ... other existing config
});在SDK 10.25.0+中,指标功能默认启用。除非用户需要禁用或过滤,否则无需修改配置。
Sentry.init()初始化文件位置:
- Next.js:、
instrumentation-client.ts、sentry.server.config.tssentry.edge.config.ts - React:、
src/index.tsx或专门的Sentry配置文件src/main.tsx - Node.js:入口文件或专门的Sentry配置文件
- 浏览器:入口文件或配置文件
可选:显式启用(非必须):
javascript
import * as Sentry from "@sentry/nextjs"; // 或@sentry/react、@sentry/node
Sentry.init({
dsn: "YOUR_DSN_HERE",
// 指标默认启用,可显式声明
enableMetrics: true,
// ... 其他现有配置
});Step 3: Add Metric Filtering (Optional)
步骤3:添加指标过滤(可选)
If user wants to filter metrics before sending:
javascript
Sentry.init({
dsn: "YOUR_DSN_HERE",
beforeSendMetric: (metric) => {
// Drop metrics with sensitive attributes
if (metric.attributes?.sensitive === true) {
return null;
}
// Remove specific attribute before sending
if (metric.attributes?.internal) {
delete metric.attributes.internal;
}
return metric;
},
});如果用户需要在发送前过滤指标:
javascript
Sentry.init({
dsn: "YOUR_DSN_HERE",
beforeSendMetric: (metric) => {
// 丢弃包含敏感属性的指标
if (metric.attributes?.sensitive === true) {
return null;
}
// 发送前移除特定属性
if (metric.attributes?.internal) {
delete metric.attributes.internal;
}
return metric;
},
});Step 4: Disable Metrics (If Requested)
步骤4:禁用指标(如果用户要求)
If user explicitly wants to disable metrics:
javascript
Sentry.init({
dsn: "YOUR_DSN_HERE",
enableMetrics: false,
});如果用户明确需要禁用指标:
javascript
Sentry.init({
dsn: "YOUR_DSN_HERE",
enableMetrics: false,
});JavaScript Metrics API Examples
JavaScript指标API示例
Provide these examples to the user based on their use case:
根据用户的使用场景提供以下示例:
Counter Examples
计数器示例
javascript
// Basic counter - increment by 1
Sentry.metrics.count("button_click", 1);
// Counter with attributes for filtering/grouping
Sentry.metrics.count("api_call", 1, {
attributes: {
endpoint: "/api/users",
method: "GET",
status_code: 200,
},
});
// Counter for errors
Sentry.metrics.count("checkout_error", 1, {
attributes: {
error_type: "payment_declined",
payment_provider: "stripe",
},
});
// Counter for business events
Sentry.metrics.count("email_sent", 1, {
attributes: {
template: "welcome",
recipient_type: "new_user",
},
});javascript
// 基础计数器 - 增量为1
Sentry.metrics.count("button_click", 1);
// 带属性的计数器,用于过滤/分组
Sentry.metrics.count("api_call", 1, {
attributes: {
endpoint: "/api/users",
method: "GET",
status_code: 200,
},
});
// 错误计数器
Sentry.metrics.count("checkout_error", 1, {
attributes: {
error_type: "payment_declined",
payment_provider: "stripe",
},
});
// 业务事件计数器
Sentry.metrics.count("email_sent", 1, {
attributes: {
template: "welcome",
recipient_type: "new_user",
},
});Gauge Examples
仪表盘示例
javascript
// Basic gauge
Sentry.metrics.gauge("queue_depth", 42);
// Memory usage gauge
Sentry.metrics.gauge("memory_usage", process.memoryUsage().heapUsed, {
unit: "byte",
attributes: {
process: "main",
},
});
// Connection pool gauge
Sentry.metrics.gauge("db_connections", 15, {
attributes: {
pool: "primary",
max_connections: 100,
},
});
// Active users gauge
Sentry.metrics.gauge("active_users", currentUserCount, {
attributes: {
region: "us-east",
},
});javascript
// 基础仪表盘
Sentry.metrics.gauge("queue_depth", 42);
// 内存使用量仪表盘
Sentry.metrics.gauge("memory_usage", process.memoryUsage().heapUsed, {
unit: "byte",
attributes: {
process: "main",
},
});
// 连接池仪表盘
Sentry.metrics.gauge("db_connections", 15, {
attributes: {
pool: "primary",
max_connections: 100,
},
});
// 活跃用户数仪表盘
Sentry.metrics.gauge("active_users", currentUserCount, {
attributes: {
region: "us-east",
},
});Distribution Examples
分布统计示例
javascript
// Response time distribution
Sentry.metrics.distribution("response_time", 187.5, {
unit: "millisecond",
attributes: {
endpoint: "/api/products",
method: "GET",
},
});
// Cart value distribution
Sentry.metrics.distribution("cart_value", 149.99, {
unit: "usd",
attributes: {
customer_tier: "premium",
},
});
// Query duration distribution
Sentry.metrics.distribution("db_query_duration", 45.2, {
unit: "millisecond",
attributes: {
query_type: "select",
table: "users",
},
});
// File size distribution
Sentry.metrics.distribution("upload_size", 2048576, {
unit: "byte",
attributes: {
file_type: "image",
},
});javascript
// 响应时间分布统计
Sentry.metrics.distribution("response_time", 187.5, {
unit: "millisecond",
attributes: {
endpoint: "/api/products",
method: "GET",
},
});
// 购物车金额分布统计
Sentry.metrics.distribution("cart_value", 149.99, {
unit: "usd",
attributes: {
customer_tier: "premium",
},
});
// 查询耗时分布统计
Sentry.metrics.distribution("db_query_duration", 45.2, {
unit: "millisecond",
attributes: {
query_type: "select",
table: "users",
},
});
// 文件大小分布统计
Sentry.metrics.distribution("upload_size", 2048576, {
unit: "byte",
attributes: {
file_type: "image",
},
});Manual Flush
手动刷新
javascript
// Force pending metrics to send immediately
await Sentry.flush();
// Useful before process exit or after critical operations
process.on("beforeExit", async () => {
await Sentry.flush();
});javascript
// 强制立即发送待处理的指标
await Sentry.flush();
// 在进程退出前或关键操作后使用
process.on("beforeExit", async () => {
await Sentry.flush();
});Python Configuration
Python配置
Minimum SDK Version
最低SDK版本
- version
sentry-sdk2.44.0+
- 版本
sentry-sdk2.44.0+
Step 1: Verify SDK Version
步骤1:验证SDK版本
bash
pip show sentry-sdk | grep VersionIf version is below 2.44.0:
bash
pip install --upgrade sentry-sdkbash
pip show sentry-sdk | grep Version如果版本低于2.44.0:
bash
pip install --upgrade sentry-sdkStep 2: Verify Metrics Are Enabled
步骤2:验证指标功能已启用
Metrics are enabled by default in SDK 2.44.0+. No changes required unless filtering is needed.
Common init locations:
- Django:
settings.py - Flask: or
app.py__init__.py - FastAPI:
main.py - General: Entry point or dedicated config file
在SDK 2.44.0+中,指标功能默认启用。除非需要过滤,否则无需修改配置。
常见初始化位置:
- Django:
settings.py - Flask:或
app.py__init__.py - FastAPI:
main.py - 通用项目:入口文件或专门的配置文件
Step 3: Add Metric Filtering (Optional)
步骤3:添加指标过滤(可选)
python
import sentry_sdk
def before_send_metric(metric, hint):
# Drop metrics with specific attributes
if metric.get("attributes", {}).get("sensitive"):
return None
# Modify metric before sending
if metric.get("attributes", {}).get("internal"):
del metric["attributes"]["internal"]
return metric
sentry_sdk.init(
dsn="YOUR_DSN_HERE",
before_send_metric=before_send_metric,
)python
import sentry_sdk
def before_send_metric(metric, hint):
# 丢弃包含特定属性的指标
if metric.get("attributes", {}).get("sensitive"):
return None
# 发送前修改指标
if metric.get("attributes", {}).get("internal"):
del metric["attributes"]["internal"]
return metric
sentry_sdk.init(
dsn="YOUR_DSN_HERE",
before_send_metric=before_send_metric,
)Python Metrics API Examples
Python指标API示例
Counter Examples
计数器示例
python
import sentry_sdkpython
import sentry_sdkBasic counter
基础计数器
sentry_sdk.metrics.count("button_click", 1)
sentry_sdk.metrics.count("button_click", 1)
Counter with attributes
带属性的计数器
sentry_sdk.metrics.count(
"api_call",
1,
attributes={
"endpoint": "/api/users",
"method": "GET",
"status_code": 200,
}
)
sentry_sdk.metrics.count(
"api_call",
1,
attributes={
"endpoint": "/api/users",
"method": "GET",
"status_code": 200,
}
)
Counter for errors
错误计数器
sentry_sdk.metrics.count(
"checkout_error",
1,
attributes={
"error_type": "payment_declined",
"payment_provider": "stripe",
}
)
sentry_sdk.metrics.count(
"checkout_error",
1,
attributes={
"error_type": "payment_declined",
"payment_provider": "stripe",
}
)
Business event counter
业务事件计数器
sentry_sdk.metrics.count(
"email_sent",
5, # Can increment by more than 1
attributes={
"template": "newsletter",
"batch_id": "batch_123",
}
)
undefinedsentry_sdk.metrics.count(
"email_sent",
5, # 增量可大于1
attributes={
"template": "newsletter",
"batch_id": "batch_123",
}
)
undefinedGauge Examples
仪表盘示例
python
import sentry_sdk
import psutilpython
import sentry_sdk
import psutilBasic gauge
基础仪表盘
sentry_sdk.metrics.gauge("queue_depth", 42)
sentry_sdk.metrics.gauge("queue_depth", 42)
Memory usage gauge
内存使用量仪表盘
sentry_sdk.metrics.gauge(
"memory_usage",
psutil.virtual_memory().used,
unit="byte",
attributes={"host": "web-01"}
)
sentry_sdk.metrics.gauge(
"memory_usage",
psutil.virtual_memory().used,
unit="byte",
attributes={"host": "web-01"}
)
Database connection gauge
数据库连接仪表盘
sentry_sdk.metrics.gauge(
"db_connections",
connection_pool.size(),
attributes={
"pool": "primary",
"max": connection_pool.max_size,
}
)
sentry_sdk.metrics.gauge(
"db_connections",
connection_pool.size(),
attributes={
"pool": "primary",
"max": connection_pool.max_size,
}
)
Cache hit rate gauge
缓存命中率仪表盘
sentry_sdk.metrics.gauge(
"cache_hit_rate",
0.85,
attributes={"cache": "redis"}
)
undefinedsentry_sdk.metrics.gauge(
"cache_hit_rate",
0.85,
attributes={"cache": "redis"}
)
undefinedDistribution Examples
分布统计示例
python
import sentry_sdk
import timepython
import sentry_sdk
import timeResponse time distribution
响应时间分布统计
start = time.time()
start = time.time()
... do work ...
... 执行操作 ...
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
"response_time",
duration_ms,
unit="millisecond",
attributes={
"endpoint": "/api/products",
"method": "GET",
}
)
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
"response_time",
duration_ms,
unit="millisecond",
attributes={
"endpoint": "/api/products",
"method": "GET",
}
)
Order value distribution
订单金额分布统计
sentry_sdk.metrics.distribution(
"order_value",
order.total,
unit="usd",
attributes={
"customer_tier": customer.tier,
"payment_method": order.payment_method,
}
)
sentry_sdk.metrics.distribution(
"order_value",
order.total,
unit="usd",
attributes={
"customer_tier": customer.tier,
"payment_method": order.payment_method,
}
)
Query duration distribution
查询耗时分布统计
sentry_sdk.metrics.distribution(
"db_query_duration",
query_time_ms,
unit="millisecond",
attributes={
"query_type": "select",
"table": "orders",
}
)
---sentry_sdk.metrics.distribution(
"db_query_duration",
query_time_ms,
unit="millisecond",
attributes={
"query_type": "select",
"table": "orders",
}
)
---Framework-Specific Notes
框架专属说明
Next.js
Next.js
- Metrics work on both client and server
- Consider tracking in API routes and server components
- Use attributes to distinguish client vs server metrics
- 指标在客户端和服务端均生效
- 考虑在API路由和服务端组件中添加追踪
- 使用属性区分客户端和服务端指标
React (Browser)
React(浏览器)
- Track user interactions (clicks, form submissions)
- Monitor component render performance
- Be mindful of metric volume from client-side
- 追踪用户交互(点击、表单提交)
- 监控组件渲染性能
- 注意客户端指标的发送量
Node.js
Node.js
- Track API response times, queue depths, background job metrics
- Use gauges for resource monitoring
- Flush metrics before process exit
- 追踪API响应时间、队列深度、后台任务指标
- 使用仪表盘监控资源使用情况
- 进程退出前刷新指标
Django
Django
- Track view response times
- Monitor database query performance
- Use middleware for automatic request metrics
- 追踪视图响应时间
- 监控数据库查询性能
- 使用中间件自动收集请求指标
Flask/FastAPI
Flask/FastAPI
- Track endpoint performance
- Monitor external API call durations
- Use decorators or middleware for automatic instrumentation
- 追踪接口性能
- 监控外部API调用耗时
- 使用装饰器或中间件自动埋点
Common Units
常用单位
Use these units for better readability in Sentry dashboard:
| Category | Units |
|---|---|
| Time | |
| Size | |
| Currency | |
| Rate | |
| Other | |
使用以下单位可提升Sentry仪表盘的可读性:
| 分类 | 单位 |
|---|---|
| 时间 | |
| 大小 | |
| 货币 | |
| 比率 | |
| 其他 | |
Best Practices
最佳实践
DO Use Metrics For:
推荐使用指标追踪:
- Business KPIs (orders, signups, revenue)
- Application health (error rates, latency)
- Resource utilization (queue depth, connections)
- User actions (clicks, page views, feature usage)
- 业务KPI(订单量、注册量、营收)
- 应用健康状况(错误率、延迟)
- 资源利用率(队列深度、连接数)
- 用户行为(点击量、页面浏览量、功能使用情况)
DON'T Use Metrics For:
不推荐使用指标追踪:
- Infrastructure monitoring (use dedicated tools)
- Log aggregation (use Sentry Logs instead)
- Full request tracing (use Sentry Tracing)
- High-cardinality data in attributes
- 基础设施监控(使用专门工具)
- 日志聚合(使用Sentry Logs)
- 完整请求链路追踪(使用Sentry Tracing)
- 属性中包含高基数数据
Naming Conventions:
命名规范:
undefinedundefinedGood - descriptive, namespaced
推荐 - 描述清晰、带命名空间
api.request.duration
checkout.cart.value
user.signup.completed
api.request.duration
checkout.cart.value
user.signup.completed
Avoid - vague, inconsistent
避免 - 模糊、不一致
duration
value1
myMetric
undefinedduration
value1
myMetric
undefinedAttribute Guidelines:
属性指南:
- Keep cardinality low (avoid user IDs, request IDs)
- Use consistent attribute names across metrics
- Include relevant context for filtering
- Avoid sensitive data in attributes
- 保持低基数(避免用户ID、请求ID)
- 指标间使用一致的属性名称
- 添加用于过滤的相关上下文
- 属性中避免包含敏感数据
Instrumentation Patterns
埋点模式
Timing Helper (JavaScript)
计时工具(JavaScript)
javascript
async function withTiming(name, fn, attributes = {}) {
const start = performance.now();
try {
return await fn();
} finally {
const duration = performance.now() - start;
Sentry.metrics.distribution(name, duration, {
unit: "millisecond",
attributes,
});
}
}
// Usage
const result = await withTiming(
"api.external.duration",
() => fetch("https://api.example.com/data"),
{ service: "example-api" }
);javascript
async function withTiming(name, fn, attributes = {}) {
const start = performance.now();
try {
return await fn();
} finally {
const duration = performance.now() - start;
Sentry.metrics.distribution(name, duration, {
unit: "millisecond",
attributes,
});
}
}
// 使用示例
const result = await withTiming(
"api.external.duration",
() => fetch("https://api.example.com/data"),
{ service: "example-api" }
);Timing Decorator (Python)
计时装饰器(Python)
python
import functools
import time
import sentry_sdk
def track_duration(metric_name, **extra_attrs):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
try:
return func(*args, **kwargs)
finally:
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
metric_name,
duration_ms,
unit="millisecond",
attributes=extra_attrs,
)
return wrapper
return decoratorpython
import functools
import time
import sentry_sdk
def track_duration(metric_name, **extra_attrs):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
try:
return func(*args, **kwargs)
finally:
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
metric_name,
duration_ms,
unit="millisecond",
attributes=extra_attrs,
)
return wrapper
return decorator
// 使用示例
@track_duration("db.query.duration", query_type="user_lookup")
def get_user_by_id(user_id):
return db.query(User).filter(User.id == user_id).first()Usage
请求中间件(Express/Node.js)
@track_duration("db.query.duration", query_type="user_lookup")
def get_user_by_id(user_id):
return db.query(User).filter(User.id == user_id).first()
undefinedjavascript
function metricsMiddleware(req, res, next) {
const start = performance.now();
res.on("finish", () => {
const duration = performance.now() - start;
Sentry.metrics.distribution("http.request.duration", duration, {
unit: "millisecond",
attributes: {
method: req.method,
route: req.route?.path || req.path,
status_code: res.statusCode,
},
});
Sentry.metrics.count("http.request.count", 1, {
attributes: {
method: req.method,
status_code: res.statusCode,
},
});
});
next();
}
app.use(metricsMiddleware);Request Middleware (Express/Node.js)
Django中间件
javascript
function metricsMiddleware(req, res, next) {
const start = performance.now();
res.on("finish", () => {
const duration = performance.now() - start;
Sentry.metrics.distribution("http.request.duration", duration, {
unit: "millisecond",
attributes: {
method: req.method,
route: req.route?.path || req.path,
status_code: res.statusCode,
},
});
Sentry.metrics.count("http.request.count", 1, {
attributes: {
method: req.method,
status_code: res.statusCode,
},
});
});
next();
}
app.use(metricsMiddleware);python
import time
import sentry_sdk
class SentryMetricsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.time()
response = self.get_response(request)
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
"http.request.duration",
duration_ms,
unit="millisecond",
attributes={
"method": request.method,
"path": request.path,
"status_code": response.status_code,
},
)
return response
// 在settings.py的MIDDLEWARE中添加Django Middleware
验证步骤
python
import time
import sentry_sdk
class SentryMetricsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.time()
response = self.get_response(request)
duration_ms = (time.time() - start) * 1000
sentry_sdk.metrics.distribution(
"http.request.duration",
duration_ms,
unit="millisecond",
attributes={
"method": request.method,
"path": request.path,
"status_code": response.status_code,
},
)
return response配置完成后,提供以下验证步骤:
Add to MIDDLEWARE in settings.py
JavaScript验证
---javascript
// 临时添加以下代码进行测试
Sentry.metrics.count("test_metric", 1, {
attributes: { test: true },
});
Sentry.metrics.gauge("test_gauge", 42);
Sentry.metrics.distribution("test_distribution", 100, {
unit: "millisecond",
});
// 强制立即发送
await Sentry.flush();Verification Steps
Python验证
After setup, provide these verification instructions:
python
import sentry_sdk
sentry_sdk.metrics.count("test_metric", 1, attributes={"test": True})
sentry_sdk.metrics.gauge("test_gauge", 42)
sentry_sdk.metrics.distribution("test_distribution", 100, unit="millisecond")告知用户前往Sentry控制台的Metrics板块,确认指标已正常上报。
JavaScript Verification
常见问题与解决方案
—
问题:指标未出现在Sentry中
javascript
// Add this temporarily to test
Sentry.metrics.count("test_metric", 1, {
attributes: { test: true },
});
Sentry.metrics.gauge("test_gauge", 42);
Sentry.metrics.distribution("test_distribution", 100, {
unit: "millisecond",
});
// Force flush to send immediately
await Sentry.flush();解决方案:
- 验证SDK版本满足最低要求(JS:10.25.0+,Python:2.44.0+)
- 确认指标功能未被禁用()
enableMetrics: false - 检查DSN是否正确
- 等待几分钟 - 指标会被缓冲后再发送
- 尝试手动刷新:或检查聚合窗口
await Sentry.flush()
Python Verification
问题:发送的指标数量过多
python
import sentry_sdk
sentry_sdk.metrics.count("test_metric", 1, attributes={"test": True})
sentry_sdk.metrics.gauge("test_gauge", 42)
sentry_sdk.metrics.distribution("test_distribution", 100, unit="millisecond")Tell user to check their Sentry dashboard under Metrics section to verify metrics are arriving.
解决方案:
- 使用过滤不必要的指标
beforeSendMetric - 降低属性的基数
- 在高流量路径上对指标进行采样
- 在客户端先聚合再发送
Common Issues and Solutions
问题:收到高基数警告
Issue: Metrics not appearing in Sentry
—
Solutions:
- Verify SDK version meets minimum requirements (JS: 10.25.0+, Python: 2.44.0+)
- Ensure metrics aren't disabled ()
enableMetrics: false - Check DSN is correct
- Wait a few minutes - metrics are buffered before sending
- Try manual flush: or check aggregation window
await Sentry.flush()
解决方案:
- 避免在属性中包含用户ID、请求ID、时间戳
- 使用分类而非具体值
- 限制属性值的唯一组合数量
Issue: Too many metrics being sent
问题:指标未与链路追踪关联
Solutions:
- Use to filter unnecessary metrics
beforeSendMetric - Reduce attribute cardinality
- Sample metrics on high-traffic paths
- Aggregate client-side before sending
解决方案:
- 确保指标功能与链路追踪同时启用
- 在追踪Span内上报指标
- 检查链路采样规则是否丢弃了相关追踪数据
Issue: High cardinality warnings
总结检查清单
Solutions:
- Avoid user IDs, request IDs, timestamps in attributes
- Use categories instead of specific values
- Limit unique attribute value combinations
配置完成后提供以下检查清单:
markdown
undefinedIssue: Metrics not linked to traces
Sentry Metrics配置完成
—
已完成的配置:
Solutions:
- Ensure tracing is enabled alongside metrics
- Emit metrics within traced spans
- Check that trace sampling isn't dropping related traces
- 验证SDK版本(JS:10.25.0+,Python:2.44.0+)
- 指标功能已启用(默认)或已显式配置
- 已配置指标过滤(如果用户要求)
Summary Checklist
已添加的埋点:
Provide this checklist after setup:
markdown
undefined- 事件/行为的计数器指标
- 瞬时值的仪表盘指标
- 时间/数值的分布统计指标
- 已指定合适的单位
- 已添加有意义的属性
Sentry Metrics Setup Complete
后续步骤:
Configuration Applied:
—
- SDK version verified (JS: 10.25.0+, Python: 2.44.0+)
- Metrics enabled (default) or explicitly configured
- Metric filtering configured (if requested)
- 运行应用
- 触发会上报指标的操作
- 查看Sentry控制台 > Metrics板块
- 基于指标创建仪表盘和告警
---Instrumentation Added:
快速参考
- Counter metrics for events/actions
- Gauge metrics for point-in-time values
- Distribution metrics for timing/values
- Appropriate units specified
- Meaningful attributes added
| 平台 | SDK版本 | API命名空间 |
|---|---|---|
| JavaScript | 10.25.0+ | |
| Python | 2.44.0+ | |
| 方法 | JavaScript | Python |
|---|---|---|
| 计数器 | | |
| 仪表盘 | | |
| 分布统计 | | |
| 选项 | JavaScript | Python |
|---|---|---|
| 单位 | | |
| 属性 | | |
Next Steps:
—
- Run your application
- Trigger actions that emit metrics
- Check Sentry dashboard > Metrics section
- Create dashboards and alerts based on metrics
---—
Quick Reference
—
| Platform | SDK Version | API Namespace |
|---|---|---|
| JavaScript | 10.25.0+ | |
| Python | 2.44.0+ | |
| Method | JavaScript | Python |
|---|---|---|
| Counter | | |
| Gauge | | |
| Distribution | | |
| Option | JavaScript | Python |
|---|---|---|
| Unit | | |
| Attributes | | |
—