简体   繁体   English

在 Application Insights 指标中为每个请求添加自定义属性

[英]Adding custom properties for each request in Application Insights metrics

I d'like to add custom properties to metrics taken by Application Insights to each request of my app.我想将自定义属性添加到 Application Insights我的应用程序的每个请求所采用的指标。 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.例如,我想添加用户登录和租户代码,例如我可以在 Azure 门户中对指标进行分段/分组。

The relevant doc page seems to be this one : Set default property values相关的文档页面似乎是这个: 设置默认属性值

But the example is for an event (ie gameTelemetry.TrackEvent("WinGame"); ), not for an HTTP request :但该示例是针对事件(即gameTelemetry.TrackEvent("WinGame"); ),而不是针对 HTTP 请求:

var context = new TelemetryContext();
context.Properties["Game"] = currentGame.Name;
var gameTelemetry = new TelemetryClient(context);
gameTelemetry.TrackEvent("WinGame");

My questions :我的问题:

  1. 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 ?请求的相关代码是什么,因为我目前没有特定代码(它似乎由 App Insights SDK 自动管理):仅创建TelemetryContext足够了吗? Should I create also a TelemetryClient and if so, should I link it to the current request ?我还应该创建一个TelemetryClient吗,如果是这样,我应该将它链接到当前请求吗? How ?如何 ?
  2. Where should I put this code ?我应该把这段代码放在哪里? Is it ok in the Application_BeginRequest method of global.asax ?global.asaxApplication_BeginRequest方法中可以吗?

It looks like adding new properties to existing request is possible using ITelemetryInitializer as mentioned here .它看起来像增加新的特性,以现有的要求可能使用ITelemetryInitializer提到这里

I created sample class as given below and added new property called "LoggedInUser" to request telemetry.我创建了如下所示的示例类,并添加了名为“LoggedInUser”的新属性来请求遥测。

public class CustomTelemetry : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        if (requestTelemetry == null) return;
        requestTelemetry.Properties.Add("LoggedInUserName", "DummyUser");

    }
}

Register this class at application start event.在应用程序启动事件中注册此类。 Example below is carved out of sample MVC application I created下面的示例是从我创建的示例 MVC 应用程序中雕刻出来的

 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());
    }
}

Now you can see custom property "LoggedInUserName" is displayed under Custom group of request properties.现在您可以看到自定义属性“LoggedInUserName”显示在请求属性的自定义组下。 (please refer screen grab below) (请参考下面的屏幕截图)

Appinsight with custom property具有自定义属性的 Appinsight

Related to the first question "how to add custom event to my request / what is the relevant code to a request", I think the main confusion here is related to the naming.关于第一个问题“如何向我的请求添加自定义事件/请求的相关代码是什么”,我认为这里的主要混淆与命名有关。

The first thing that we need to point out is that there are different kinds of information that we can capture with Application Insights:我们需要指出的第一件事是,我们可以使用 Application Insights 捕获不同类型的信息:

  1. Custom Event自定义事件
  2. Request要求
  3. Exception例外
  4. Trace痕迹
  5. Page View页面预览
  6. Dependency依赖

Once we know this, we can say that TrackEvent is related to "Custom Events", as TrackRequest is related to Requests.一旦我们知道这一点,我们就可以说 TrackEvent 与“自定义事件”相关,因为 TrackRequest 与请求相关。

When we want to save a request, what we need to do is the following:当我们想要保存一个请求时,我们需要做的是:

 var request = new RequestTelemetry();
 var client = new TelemetryClient();
 request.Name = "My Request";
 client.TrackRequest(request);

So let's imagine that your user login and tenant code both are strings.因此,让我们假设您的用户登录名和租户代码都是字符串。 We could make a new request just to log this information using the following code:我们可以使用以下代码发出一个新请求来记录此信息:

public void LogUserNameAndTenant(string userName, string tenantCode)
{
    var request = new RequestTelemetry();

    request.Name = "My Request";
    request.Context.Properties["User Name"] = userName;
    request.Context.Properties["Tenant Code"] = tenantCode;

    var client = new TelemetryClient();
    client.TrackRequest(request);
}

Doing just a TelemetryContext will not be enough, because we need a way to send the information, and that's where the TelemetryClient gets in place.只做 TelemetryContext 是不够的,因为我们需要一种发送信息的方法,这就是 TelemetryClient 就位的地方。

I hope it helps.我希望它有帮助。

You can use the static HttpContext.Current 's Items dictionary as a short term (near stateless) storage space to deliver your custom property values into the default telemetry handler with a custom ITelemetryInitializer您可以使用静态HttpContext.CurrentItems字典作为短期(接近无状态)存储空间,通过自定义ITelemetryInitializer将自定义属性值传递到默认遥测处理程序中

Implement handler实施处理程序

class AppInsightCustomProps : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        // Is this a TrackRequest() ?
        if (requestTelemetry == null) return;

        var httpCtx = HttpContext.Current;
        if (httpCtx != null)
        {
            var customPropVal = (string)httpCtx.Items["PerRequestMyCustomProp"];
            if (!string.IsNullOrWhiteSpace(customPropVal))
            {
                requestTelemetry.Properties["MyCustomProp"] = customPropVal;
            }
        }
    }
}

Hook it in. Put this inside Application_Start in global.asax.cs挂钩。把它放在global.asax.cs Application_Start

TelemetryConfiguration.Active.TelemetryInitializers.Add(new AppInsightCustomProps());

Program the desired custom property, anywhere in your request pipeline have something like对所需的自定义属性进行编程,请求管道中的任何位置都有类似的内容

if (HttpContext.Current != null)
{
    HttpContext.Current.Items["PerRequestMyCustomProp"] = myCustomPropValue;
}

As mentioned by Alan, you could implement the IContextInitializer interface to add custom properties to ALL telemetry sent by Application Insights.正如 Alan 所提到的,您可以实现IContextInitializer接口以向 Application Insights 发送的所有遥测添加自定义属性。 However, I would also suggest looking into the ITelemtryInitializer interface.但是,我还建议查看ITelemtryInitializer接口。 It is very similar to the context initializer, but it is called for every piece of telemetry sent rather than only at the creation of a telemetry client.它与上下文初始值设定项非常相似,但它会在每条遥测发送时调用,而不仅仅是在创建遥测客户端时调用。 This seems more useful to me for logging property values that might change over the lifetime of your app such as user and tenant related info like you had mentioned.这对我来说对于记录可能在应用程序的生命周期内发生变化的属性值更有用,例如您提到的用户和租户相关信息。

I hope that helps you out.我希望能帮到你。 Here is a blog post with an example of using the ITelemetryInitializer .这是一篇博客文章,其中包含使用ITelemetryInitializer的示例。

In that doc, scroll down a few lines to where it talks about creating an implementation of IContextInitializer.在该文档中,向下滚动几行到它谈到创建 IContextInitializer 的实现的地方。 You can call that in any method that will be called before telemetry starts rolling.您可以在遥测开始滚动之前调用的任何方法中调用它。

Your custom properties will be added to all events, exceptions, metrics, requests, everything.您的自定义属性将添加到所有事件、异常、指标、请求等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM