问题描述
我想将自定义属性添加到 Application Insights应用的每个请求所采用的指标中.例如,我想添加用户登录和租户代码,例如我可以在 Azure 门户中对指标进行分段/分组.
I d'like to add custom properties to metrics taken by Application Insights to each request of my app. For example, I want to add the user login and the tenant code, such as I can segment/group the metrics in the Azure portal.
相关的文档页面似乎是这个:设置默认属性值
The relevant doc page seems to be this one : Set default property values
但该示例是针对事件(即 gameTelemetry.TrackEvent("WinGame");
),而不是针对 HTTP 请求:
But the example is for an event (i.e. gameTelemetry.TrackEvent("WinGame");
), not for an HTTP request :
var context = new TelemetryContext();
context.Properties["Game"] = currentGame.Name;
var gameTelemetry = new TelemetryClient(context);
gameTelemetry.TrackEvent("WinGame");
我的问题:
- 请求的相关代码是什么,因为我目前没有特定代码(它似乎由 App Insights SDK 自动管理):仅创建一个
TelemetryContext
就足够了吗?我还应该创建一个TelemetryClient
吗?如果是,我应该将它链接到当前请求吗?怎么样? - 我应该把这段代码放在哪里?
global.asax
的Application_BeginRequest
方法可以吗?
- What is the relevant code for a request, as I have no specific code at this time (it seems to be automatically managed by the App Insights SDK) : Is just creating a
TelemetryContext
sufficient ? Should I create also aTelemetryClient
and if so, should I link it to the current request ? How ? - Where should I put this code ? Is it ok in the
Application_BeginRequest
method ofglobal.asax
?
推荐答案
看起来可以使用提到的 ITelemetryInitializer 向现有请求添加新属性 这里.
It looks like adding new properties to existing request is possible using ITelemetryInitializer as mentioned here.
我创建了如下所示的示例类,并添加了名为LoggedInUser"的新属性来请求遥测.
I created sample class as given below and added new property called "LoggedInUser" to request telemetry.
public class CustomTelemetry : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var requestTelemetry = telemetry as RequestTelemetry;
if (requestTelemetry == null) return;
requestTelemetry.Properties.Add("LoggedInUserName", "DummyUser");
}
}
在应用程序启动事件中注册此类.下面的示例是从我创建的示例 MVC 应用程序中提取的
Register this class at application start event. Example below is carved out of sample MVC application I created
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
TelemetryConfiguration.Active.TelemetryInitializers
.Add(new CustomTelemetry());
}
}
现在您可以看到自定义属性LoggedInUserName"显示在自定义请求属性组下.(请参阅下面的屏幕截图)
Now you can see custom property "LoggedInUserName" is displayed under Custom group of request properties. (please refer screen grab below)
Appinsight 与自定义属性
这篇关于在 Application Insights 指标中为每个请求添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!