Adding custom properties for each request in Application Insights metrics

后端 未结 5 2000
孤街浪徒
孤街浪徒 2020-11-29 03:42

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 ten

5条回答
  •  眼角桃花
    2020-11-29 04:42

    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:

    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.

    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.

    I hope it helps.

提交回复
热议问题