问题
How can I add custom properties to the default request telemetry in application insights? I was able to do that by creating new telemetry client but I would like NOT to do that as it creates duplicate events.
回答1:
Make your own custom TelemetryInitializer. https://azure.microsoft.com/en-us/documentation/articles/app-insights-api-custom-events-metrics/#telemetry-initializers.
snipped from the above article:
using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
namespace MvcWebRole.Telemetry
{
/*
* Custom TelemetryInitializer that overrides the default SDK
* behavior of treating response codes >= 400 as failed requests
*
*/
public class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var requestTelemetry = telemetry as RequestTelemetry;
// Is this a TrackRequest() ?
if (requestTelemetry == null) return;
int code;
bool parsed = Int32.TryParse(requestTelemetry.ResponseCode, out code);
if (!parsed) return;
if (code >= 400 && code < 500)
{
// If we set the Success property, the SDK won't change it:
requestTelemetry.Success = true;
// Allow us to filter these requests in the portal:
requestTelemetry.Context.Properties["Overridden400s"] = "true";
}
// else leave the SDK to set the Success property
}
}
}
then load that initializer either in the config file or via code, see the doc above for those details.
来源:https://stackoverflow.com/questions/32375903/adding-custom-properties-to-default-request-telemetry