跳转到内容
Telemetry
浏览文档

SDK更新于 2026年10月1日阅读约需 3 分钟

让编程智能体使用这篇文档

打开 Claude Code、Codex、Cursor 或其他编码代理的集中提示包,然后将其适应此处介绍的工作流程。

本页内容
  1. 配置命名客户端
  2. 发送一个结构化事件
  3. 运行SQL
  4. 失败和重试策略
  5. 验证集成

.NET HTTP 集成

Telemetry 不发布本机 .NET SDK。当 ASP.NET Core 服务、工作线程或计划作业需要结构化事件引入时,通过应用程序拥有的 HttpClient 或 IHttpClientFactory 配置使用 HTTP API。

应用程序仍然负责连接重用、超时、重试、序列化、取消以及可观测性故障是否可能影响客户工作流程。

配置命名客户端

builder.Services.AddHttpClient("telemetry", client =>
{
    client.BaseAddress = new Uri("https://api.telemetry.sh");
    client.Timeout = TimeSpan.FromSeconds(3);
});

builder.Services.AddHttpClient("telemetry-query", client =>
{
    client.BaseAddress = new Uri("https://api.telemetry.sh");
    client.Timeout = TimeSpan.FromSeconds(15);
});

从 IHttpClientFactory 解析客户端,而不是为每个事件构建新的 HttpClient。将 Telemetry 密钥存储在服务的现有秘密管理器中,并使用单独的仅摄取密钥和只读密钥,其中运行时支持摄取和查询。

发送一个结构化事件

在了解最终应用程序结果后,构建类型化、列入白名单的有效负载:

using System.Net.Http.Json;
using System.Text.Json;

var payload = new
{
    table = "api_request_completed",
    data = new
    {
        event_id = eventId,
        route_template = routeTemplate,
        method = requestMethod,
        status_code = completedStatusCode,
        status = completedStatusCode < 400 ? "success" : "error",
        latency_ms = elapsed.TotalMilliseconds,
        request_id = requestId,
        release
    }
};

try
{
    using var request = new HttpRequestMessage(HttpMethod.Post, "/log")
    {
        Content = JsonContent.Create(payload)
    };
    request.Headers.TryAddWithoutValidation("Authorization", telemetryApiKey);

    var client = httpClientFactory.CreateClient("telemetry");
    using var response = await client.SendAsync(request, cancellationToken);
    if (!response.IsSuccessStatusCode)
    {
        RecordTelemetryDeliveryFailure("telemetry_delivery_rejected");
    }
}
catch (OperationCanceledException)
{
    RecordTelemetryDeliveryFailure("telemetry_delivery_cancelled");
}
catch (Exception error) when (error is HttpRequestException
    or JsonException or NotSupportedException
    or ArgumentException or InvalidOperationException)
{
    RecordTelemetryDeliveryFailure("telemetry_delivery_failed");
}

static void RecordTelemetryDeliveryFailure(string reason)
{
    // Diagnostics must not replace the already completed application result.
    try { Console.Error.WriteLine(reason); }
    catch { }
}

请在应用操作完成后运行此示例,并使用实际的路由模板、方法和 HTTP 状态。发送失败不会覆盖应用结果;取消令牌仍保持取消状态。此示例只发送一次,不记录响应正文,也不保证数据已存储。请通过 SQL 验证送达。

使用路由模板、稳定的内部标识符和受控的错误类别。请勿序列化标头、cookie、凭据、请求正文、绑定 SQL 值、堆栈跟踪、提示、生成的内容或不受限制的异常消息。

运行SQL

使用更长的、单独限定的查询期限和读取范围的键:

下面使用独立的 telemetry-query 客户端。其超时为 15 秒,摄取客户端仍为三秒。调用方更短的取消期限仍优先生效。不要在共享客户端已开始请求后更改其超时。

var queryPayload = new
{
    query = """
        SELECT route_template, COUNT(*) AS requests
        FROM api_request_completed
        WHERE timestamp_utc >= now() - INTERVAL '24 hours'
        GROUP BY route_template
        ORDER BY requests DESC
        """
};

using var queryRequest = new HttpRequestMessage(HttpMethod.Post, "/query")
{
    Content = JsonContent.Create(queryPayload)
};
queryRequest.Headers.TryAddWithoutValidation(
    "Authorization",
    telemetryReadApiKey
);

var queryClient = httpClientFactory.CreateClient("telemetry-query");
using var queryResponse = await queryClient.SendAsync(
    queryRequest,
    queryCancellationToken
);

检查HTTP状态以及响应status、data和key_order字段。空结果是有效结果,不应被视为传输错误。

失败和重试策略

仅重试有限的瞬时故障,例如连接错误、429、502、503 和 504。应用带抖动的指数退避、限制总运行时间、尊重请求取消并重复使用相同的 event_id。不要重试未更改的架构错误或错误的凭据。

对于正常的产品分析,不要因为遥测交付失败而将成功的客户操作变成错误。对于需要持久性的计费或批准的审计事件,请提交带有业务事务的发件箱记录并从后台工作人员交付。

验证集成

发送已知的成功、失败、重试、取消和超时装置,然后检查最近的行:

SELECT timestamp_utc, event_id, route_template, method, status_code, status, latency_ms
FROM api_request_completed
ORDER BY timestamp_utc DESC
LIMIT 20;

确认每个逻辑结果的一个终端行、稳定字段类型、预期单位、UTC 时间戳以及不存在敏感内容。在生产量启用路径之前,执行 Telemetry 超时和正常工作线程关闭。

继续使用 .NET 和 Serilog 集成、日志API、速率限制和错误 和 批处理和关闭。

相关功能

记录稳定的事件名称、类型明确的字段,以及经过隐私审核的上下文。

页面作者和参考资料

Telemetry 编辑团队负责维护本文;产品团队审核功能行为、示例和适用范围。

我们如何审核文档