我正在尝试通过他们的 REST API 在应用程序洞察中发布自定义事件。
我已经创建了一个 API 密钥并在 postmand 中尝试以下操作,但它无法使用 post 方法工作 https://api.applicationinsights.io/v1/apps/appid/metadata 标头 x-api-key 并在体内传递价值,例如 { “名称”:“自定义事件”, "时间": "2024-02-12T12:00:00Z", “特性”: { “自定义属性”:“自定义值” } 但如果我没有发布任何内容,我做错了什么,有人可以帮忙吗?
看起来 ChatGPT 建议了您的方法。这是不正确的。它可能会感到困惑,因为摄取 REST API 没有记录,因此互联网上没有可供它学习的示例。
尽管 Ingestion REST API 没有正式记录,但这是一个公共合同。因此,一种方法是用任何语言编写应用程序,让它发出您想要的事件,检查有效负载(例如,使用 Fiddler),然后手动构建此类有效负载,并使用您选择的语言的常规 HTTP 客户端自行提交它.
这是一个示例程序,它使用 .NET 控制台应用程序将自定义事件发送到 Application Insights:
private static void Main(string[] args)
{
// Create the DI container.
IServiceCollection services = new ServiceCollection();
services.AddApplicationInsightsTelemetryWorkerService(
options => options.ConnectionString =
"<your connection string from Application Insights resource>");
// Build ServiceProvider.
IServiceProvider serviceProvider = services.BuildServiceProvider();
// Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();
telemetryClient.TrackEvent("Program Started",
new Dictionary<string, string>([new KeyValuePair<string, string>("key1", "value1")]));
telemetryClient.Flush();
Thread.Sleep(60000);
}
这是 HTTP 调用:
POST https://<endpoint from connection string>/v2/track HTTP/1.1
{
"name": "AppEvents",
"time": "2024-02-12T18:38:49.0743201Z",
"iKey": "<instrumentation key>",
"tags": {
"ai.application.ver": "1.0.0.0",
"ai.cloud.roleInstance": "<your instance>",
},
"data": {
"baseType": "EventData",
"baseData": {
"ver": 2,
"name": "Program Started",
"properties": {
"key1": "value1"
}
}
}
}
这是成功的响应:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
Date: Mon, 12 Feb 2024 18:50:36 GMT
Connection: close
Content-Length: 49
{
"itemsReceived": 1,
"itemsAccepted": 1,
"errors": []
}
如果出现一些错误(例如指定了无效的检测密钥),
errors
属性将有详细的解释:
{
"itemsReceived": 1,
"itemsAccepted": 0,
"errors": [
{
"index": 0,
"statusCode": 400,
"message": "Invalid instrumentation key"
}
]
}