Application Insights

De Banane Atomic
Aller à la navigationAller à la recherche

Liens

Read ApplicationInsights.conf

Cs.svg
var telemetryClient = new TelemetryClient();
// the parameterless ctor calls another ctor with TelemetryConfiguration.Active as parameter
// TelemetryConfiguration.Active reads the ApplicationInsights.config file in the working directory

// Reads a specific ApplicationInsights.config file
TelemetryConfiguration configuration = TelemetryConfiguration.CreateFromConfiguration(File.ReadAllText("C:\\ApplicationInsights.config"));
var telemetryClient = new TelemetryClient(configuration);

Dependency injection

Prism WPF application

App.xaml.cs
// classe de type PrismApplication qui hérite de PrismApplicationBase (Prism.DryIoc)
public partial class App
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        var telemetryClient = new TelemetryClient();
        containerRegistry.RegisterInstance(telemetryClient);
    }

Send telemetry to Application Insights

Cs.svg
// create a dependency
using (operation = telemetryClient.StartOperation<DependencyTelemetry>("Operation name"))
{
    // add custom properties
    operation.Telemetry.Properties.Add("Key", "Value");
}

// with a try catch finally
var operation = telemetryClient.StartOperation<DependencyTelemetry>("Operation name");
try {}
catch {}
finally
{
    // stop the operation and track telemetry
    telemetryClient.StopOperation(operation);
}

// log a trace
telemetryClient.TrackTrace("log message");

Link caller dependencies to service incoming requests

  • Adding the NuGet package Microsoft.ApplicationInsights.DependencyCollector will propagate the W3C Trace-Context from the caller (client) to the service (controller)
ApplicationInsights.config
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
    <TelemetryInitializers>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector"/>
    </TelemetryInitializers>
    <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
            <ExcludeComponentCorrelationHttpHeadersOnDomains>
                <!-- 
        Requests to the following hostnames will not be modified by adding correlation headers.         
        Add entries here to exclude additional hostnames.
        NOTE: this configuration will be lost upon NuGet upgrade.
        -->
                <Add>core.windows.net</Add>
                <Add>core.chinacloudapi.cn</Add>
                <Add>core.cloudapi.de</Add>
                <Add>core.usgovcloudapi.net</Add>
            </ExcludeComponentCorrelationHttpHeadersOnDomains>
            <IncludeDiagnosticSourceActivities>
                <Add>Microsoft.Azure.EventHubs</Add>
                <Add>Microsoft.Azure.ServiceBus</Add>
            </IncludeDiagnosticSourceActivities>
        </Add>
    </TelemetryModules>
    <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights"/>
</ApplicationInsights>

Distributed tracing and correlation through Service Bus messaging

Advanced SQL tracking to get full SQL Query

  • Add the NuGet package Microsoft.ApplicationInsights.DependencyCollector
  • Use Microsoft.Data.SqlClient instead of System.Data.SqlClient
ApplicationInsights.config
<?xml version="1.0" encoding="utf-8"?>

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
	
    <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
            <EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
        </Add>
Microsoft.Data.SqlClient v2.0.0 ne log rien dans AI, utiliser la v1.1.3

Configure the Application Insights SDK from code

.NET Console

Cs.svg
// create an empty configuration
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();

// fill the InstrumentationKey 
configuration.InstrumentationKey = "XXX";

// add TelemetryInitializers
configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

// initialize modules
InitializeDependencyTracking(configuration);

// create the TelemetryClient
var telemetryClient = new TelemetryClient(configuration);

// send data to AI
telemetryClient.TrackTrace("test");

// flush and wait a bit before quiting the console app
telemetryClient.Flush();
Thread.Sleep(500);

private static DependencyTrackingTelemetryModule InitializeDependencyTracking(TelemetryConfiguration configuration)
{
    var module = new DependencyTrackingTelemetryModule();

    // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de");
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net");
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("localhost");
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");

    // enable known dependency tracking, note that in future versions, we will extend this list. 
    // please check default settings in https://github.com/microsoft/ApplicationInsights-dotnet-server/blob/develop/WEB/Src/DependencyCollector/DependencyCollectorApplicationInsights.config.install.xdt

    module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
    module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

    // initialize the module
    module.Initialize(configuration);

    return module;
}

Non-HTTP apps/Background apps

Cs.svg
public void ConfigureServices(IServiceCollection services)
{
    // Adding TelemetryInitializers
    serviceCollection.AddSingleton<ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();

    // Create TelemetryClient
    serviceCollection.AddApplicationInsightsTelemetryWorkerService();
}

Capturing exceptions and related diagnostic data

App_Start\WebApiConfig.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        /* ... */
        config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
AiExceptionLogger.cs
public class AiExceptionLogger : ExceptionLogger
{
    public TelemetryClient AppInsights { get; set; }

    public AiExceptionLogger()
    {
        AppInsights = new TelemetryClient();
    }

    public override void Log(ExceptionLoggerContext context)
    {
        if (context != null && context.Exception != null)
        {
            AppInsights.TrackException(context.Exception);
        }
        base.Log(context);

Visualiser les données dans visual studio

Cloud Explorer → My Subcription → Application Insights → clique-droit sur My Application Insight → Search

Installation

  • Automatique: Azure web app → Monitoring → Application Insights → No data? Automatically instrument your ASP.NET app (restart required)
  • Manuel: Azure web app → Extensions → Add → Application Insights

Ajouter les paquets NuGet

  • Tous: Clique-droit sur le projet → Add → Application Insights Telemetry
  • Exception tracking: Microsoft.ApplicationInsights.Web
ApplicationInsights.config
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <TelemetryInitializers>
    <!-- ... -->
  </TelemetryInitializers>
  <TelemetryModules>
    <!-- ... -->
  </TelemetryModules>
  <TelemetryProcessors>
    <!-- ... -->
  </TelemetryProcessors>
  <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
</ApplicationInsights>
Modules Description Package Nuget
Dependency Tracking appels au bdd et services externes Microsoft.ApplicationInsights.DependencyCollector
Performance collector CPU, mémoire, charge réseau Microsoft.ApplicationInsights.PerfCounterCollector
Application Insights Diagnostics Telemetry erreur dans l'App Insight elle-même Microsoft.ApplicationInsights
Developer Mode force l'envoie des données immédiatement lorsque le debugger est attaché Microsoft.ApplicationInsights.WindowsServer
Web Request Tracking code et temps de réponse des requêtes HTTP Microsoft.ApplicationInsights.Web
Exception tracking exceptions non-gérées Microsoft.ApplicationInsights.Web
EventSource Tracking envoyer les EventSource comme des traces Microsoft.ApplicationInsights.EventSourceListener
ETW Event Tracking envoyer les événements des ETW providers comme des traces Microsoft.ApplicationInsights.EtwCollector
Microsoft.ApplicationInsights Core API pour le SDK Microsoft.ApplicationInsights

Erreurs

AI: Performance counter is not available in the web app supported list

These warnings are expected as computer level counters are not accessible from the Azure Web App environment. There's no way to turn off any particular counter from the default counters collection, so please safely ignore them as it doesn't affect anything.

AI: Server telemetry channel was not initialized

AI: Server telemetry channel was not initialized. So persistent storage is turned off. You need to call ServerTelemetryChannel.Initialize(). Currently monitoring will continue but if telemetry cannot be sent it will be dropped.

Le fichier ApplicationInsights.config est manquant.