Ruby HTTP 集成
Telemetry 的 HTTP API 与 Ruby 的标准库配合使用。这使得依赖面较小,同时将超时、重试和持久性策略置于应用程序控制之下。
配置并发送事件
require "json"
require "net/http"
require "uri"
api_key = ENV.fetch("TELEMETRY_API_KEY")
uri = URI("https://api.telemetry.sh/log")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = api_key
request["Content-Type"] = "application/json"
request.body = {
table: "api_request_completed",
data: {
event_id: "evt_request_101",
route_template: "/api/projects/:id",
method: "GET",
status_code: 200,
status: "success",
latency_ms: 184
}
}.to_json
response = Net::HTTP.start(
uri.hostname,
uri.port,
use_ssl: true,
open_timeout: 2,
read_timeout: 10
) { |http| http.request(request) }
unless response.is_a?(Net::HTTPSuccess)
raise "Telemetry log failed with HTTP #{response.code}"
end
Telemetry 添加 timestamp_utc。将密钥保留在服务器端,并且不要发送凭据、cookie、标头、请求参数、原始异常消息或私人客户内容。
发送一批
将 data 设置为数组:
request.body = {
table: "job_completed",
data: [
{
event_id: "evt_job_101",
job_name: "invoice_sync",
status: "success",
duration_ms: 912
},
{
event_id: "evt_job_102",
job_name: "invoice_sync",
status: "failed",
duration_ms: 2401,
error_type: "provider_timeout"
}
]
}.to_json
保持批次有界且模式兼容。应用程序拥有的队列还需要最大深度、最大寿命、溢出规则、重试预算和关闭期限。
运行SQL
使用读取范围的键:
uri = URI("https://api.telemetry.sh/query")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = api_key
request["Content-Type"] = "application/json"
request.body = {
query: <<~SQL
SELECT
route_template,
COUNT(*) AS requests,
ROUND(AVG(latency_ms), 0) AS avg_latency_ms
FROM api_request_completed
WHERE timestamp_utc >= now() - INTERVAL '24 hours'
GROUP BY route_template
ORDER BY requests DESC;
SQL
}.to_json
response = Net::HTTP.start(
uri.hostname,
uri.port,
use_ssl: true,
open_timeout: 2,
read_timeout: 30
) { |http| http.request(request) }
raise "Telemetry query failed with HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
result = JSON.parse(response.body)
Array(result["data"]).each do |row|
# Validate expected keys and nulls before using the row.
end
使用 异步查询API 进行大型 JSON 或 Parquet 导出。
重试和失败策略
Net::OpenTimeout 表示无法建立连接。 Net::ReadTimeout 不明确,因为服务器可能在响应丢失之前已经接受了请求。
仅重试暂时性网络故障、429、502、503 和 504。重用逻辑事件的 event_id,应用带抖动的指数退避,并限制总运行时间。不要重试未更改的无效请求。
对于正常分析,遥测中断不应取代完整的客户响应。当丢失不可接受时,将计费或批准的审计事件保留在应用程序拥有的持久发件箱中。
验证并排除故障
发送综合成功和失败事件、查询最新行并检查 GET /tables/<table>/schema。
KeyError:在服务器或工作环境中配置API密钥。401或403:更换密钥或更正其范围。400:检查表命名、JSON 形状和字段类型兼容性。- 超时:应用工作流记录的重试或回退策略,而不打印负载。
- 进程关闭:直接调用HTTP,没有后台队列需要flush;首先跟踪所需的调用或保留事件。