sentry-setup-metrics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Setup Sentry Metrics

配置Sentry Metrics

Configure Sentry's custom metrics for tracking counters, gauges, and distributions.
配置Sentry自定义指标,用于追踪计数器、仪表盘和分布指标。

Invoke This Skill When

何时调用此技能

  • User asks to "add Sentry metrics" or "track custom metrics"
  • User wants counters, gauges, or distributions
  • User asks about
    Sentry.metrics
    or
    sentry_sdk.metrics
  • 用户要求“添加Sentry指标”或“追踪自定义指标”时
  • 用户需要计数器、仪表盘或分布指标时
  • 用户询问
    Sentry.metrics
    sentry_sdk.metrics

Quick Reference

快速参考

PlatformMin SDKAPI
JavaScript10.25.0+
Sentry.metrics.*
Python2.44.0+
sentry_sdk.metrics.*
Note: Ruby does not have metrics support.
平台最低SDK版本API
JavaScript10.25.0+
Sentry.metrics.*
Python2.44.0+
sentry_sdk.metrics.*
注意: Ruby暂不支持指标功能。

Metric Types

指标类型

TypePurposeExample Use Cases
CounterCumulative countsAPI calls, clicks, errors
GaugePoint-in-time valuesQueue depth, memory, connections
DistributionStatistical valuesResponse times, cart amounts
类型用途示例场景
计数器(Counter)累计计数API调用次数、点击量、错误数
仪表盘(Gauge)瞬时值队列深度、内存占用、连接数
分布指标(Distribution)统计值响应时间、购物车金额

JavaScript Setup

JavaScript配置

Metrics are enabled by default in SDK 10.25.0+.
在SDK 10.25.0+版本中,指标功能默认启用。

Counter

计数器

javascript
Sentry.metrics.count("api_call", 1, {
  attributes: { endpoint: "/api/users", status_code: 200 },
});
javascript
Sentry.metrics.count("api_call", 1, {
  attributes: { endpoint: "/api/users", status_code: 200 },
});

Gauge

仪表盘

javascript
Sentry.metrics.gauge("queue_depth", 42, {
  unit: "none",
  attributes: { queue: "jobs" },
});
javascript
Sentry.metrics.gauge("queue_depth", 42, {
  unit: "none",
  attributes: { queue: "jobs" },
});

Distribution

分布指标

javascript
Sentry.metrics.distribution("response_time", 187.5, {
  unit: "millisecond",
  attributes: { endpoint: "/api/products" },
});
javascript
Sentry.metrics.distribution("response_time", 187.5, {
  unit: "millisecond",
  attributes: { endpoint: "/api/products" },
});

Filtering (optional)

过滤(可选)

javascript
Sentry.init({
  beforeSendMetric: (metric) => {
    if (metric.attributes?.sensitive) return null;
    return metric;
  },
});
javascript
Sentry.init({
  beforeSendMetric: (metric) => {
    if (metric.attributes?.sensitive) return null;
    return metric;
  },
});

Python Setup

Python配置

Metrics are enabled by default in SDK 2.44.0+.
在SDK 2.44.0+版本中,指标功能默认启用。

Counter

计数器

python
sentry_sdk.metrics.count("api_call", 1, attributes={"endpoint": "/api/users"})
python
sentry_sdk.metrics.count("api_call", 1, attributes={"endpoint": "/api/users"})

Gauge

仪表盘

python
sentry_sdk.metrics.gauge("queue_depth", 42, attributes={"queue": "jobs"})
python
sentry_sdk.metrics.gauge("queue_depth", 42, attributes={"queue": "jobs"})

Distribution

分布指标

python
sentry_sdk.metrics.distribution(
    "response_time", 187.5,
    unit="millisecond",
    attributes={"endpoint": "/api/products"}
)
python
sentry_sdk.metrics.distribution(
    "response_time", 187.5,
    unit="millisecond",
    attributes={"endpoint": "/api/products"}
)

Filtering (optional)

过滤(可选)

python
def before_send_metric(metric, hint):
    if metric.get("attributes", {}).get("sensitive"):
        return None
    return metric

sentry_sdk.init(dsn="YOUR_DSN", before_send_metric=before_send_metric)
python
def before_send_metric(metric, hint):
    if metric.get("attributes", {}).get("sensitive"):
        return None
    return metric

sentry_sdk.init(dsn="YOUR_DSN", before_send_metric=before_send_metric)

Common Units

常用单位

CategoryValues
Time
millisecond
,
second
,
minute
,
hour
Size
byte
,
kilobyte
,
megabyte
Currency
usd
,
eur
,
gbp
Other
none
,
percent
,
ratio
分类取值
时间
millisecond
,
second
,
minute
,
hour
大小
byte
,
kilobyte
,
megabyte
货币
usd
,
eur
,
gbp
其他
none
,
percent
,
ratio

Timing Helper Pattern

计时助手模式

JavaScript

JavaScript

javascript
async function withTiming(name, fn, attrs = {}) {
  const start = performance.now();
  try { return await fn(); }
  finally {
    Sentry.metrics.distribution(name, performance.now() - start, {
      unit: "millisecond", attributes: attrs,
    });
  }
}
javascript
async function withTiming(name, fn, attrs = {}) {
  const start = performance.now();
  try { return await fn(); }
  finally {
    Sentry.metrics.distribution(name, performance.now() - start, {
      unit: "millisecond", attributes: attrs,
    });
  }
}

Python

Python

python
import time, sentry_sdk

def track_duration(name, **attrs):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            start = time.time()
            try: return fn(*args, **kwargs)
            finally:
                sentry_sdk.metrics.distribution(
                    name, (time.time() - start) * 1000,
                    unit="millisecond", attributes=attrs
                )
        return wrapper
    return decorator
python
import time, sentry_sdk

def track_duration(name, **attrs):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            start = time.time()
            try: return fn(*args, **kwargs)
            finally:
                sentry_sdk.metrics.distribution(
                    name, (time.time() - start) * 1000,
                    unit="millisecond", attributes=attrs
                )
        return wrapper
    return decorator

Best Practices

最佳实践

  • Low cardinality: Avoid user IDs, request IDs in attributes
  • Namespaced names:
    api.request.duration
    , not
    duration
  • Flush on exit: Call
    Sentry.flush()
    before process exit
  • 低基数: 避免在属性中使用用户ID、请求ID等唯一标识
  • 命名空间命名: 使用
    api.request.duration
    而非
    duration
  • 退出时刷新: 在进程退出前调用
    Sentry.flush()

Troubleshooting

故障排除

IssueSolution
Metrics not appearingVerify SDK version, check DSN, wait for buffer flush
High cardinality warningRemove unique IDs from attributes
Too many metricsUse
beforeSendMetric
to filter
问题解决方案
指标未显示验证SDK版本、检查DSN、等待缓冲区刷新
高基数警告从属性中移除唯一ID
指标数量过多使用
beforeSendMetric
进行过滤