Application Insights .NET SDK Documentation

repository·main·Indexed 20 days ago

https://github.com/microsoft/applicationinsights-dotnet

The Application Insights .NET SDK allows developers to send telemetry data to Azure Monitor and Application Insights. Built on OpenTelemetry, it provides the TelemetryClient API for tracking events, metrics, dependencies, exceptions, requests, traces, and availability. The SDK supports .NET Framework 4.6.2+ and .NET 8.0+, offering integrations for ASP.NET Core and NLog via the Microsoft.ApplicationInsights.NLogTarget package.

Tokens
66.5K
Snippets
177
Records
234
Agent score
69%

What's inside Application Insights .NET SDK

  1. Overview of Application Insights for .NET

    main

    The Application Insights .NET SDK is used for sending telemetry data to Azure Monitor and Application Insights.

    Key architectural features:

    • Built on OpenTelemetry: The SDK utilizes OpenTelemetry as its underlying telemetry collection framework, using the Azure.Monitor.OpenTelemetry.Exporter for data transmission.
    • OpenTelemetry Extensibility: Developers can use standard OpenTelemetry patterns, such as Activity Processors, Resource Detectors, and custom instrumentation, to extend telemetry collection.
    • Unified Observability: The SDK integrates with the OpenTelemetry ecosystem, enabling telemetry to be sent to multiple backends simultaneously.
  2. What is included in Microsoft.ApplicationInsights.AspNetCore

    main

    The Microsoft.ApplicationInsights.AspNetCore package is built on OpenTelemetry and provides the following automatic instrumentation:

    Traces

    • ASP.NET Core Instrumentation: Automatic tracing for incoming HTTP requests.
    • HTTP Client Instrumentation: Automatic tracing for outgoing System.Net.Http.HttpClient requests.
    • SQL Client Instrumentation: Automatic tracing for Microsoft.Data.SqlClient and System.Data.SqlClient queries.

    Metrics

    • Application Insights Standard Metrics: Automatic collection of standard metrics.
    • Runtime-specific Metrics:
      • .NET 8.0+: Uses built-in Microsoft.AspNetCore.Hosting and System.Net.Http metrics.
      • .NET 7.0 and below: Uses OpenTelemetry instrumentation for ASP.NET Core and HTTP Client.

    Logs

    • Automatically collects logs created via Microsoft.Extensions.Logging.

    Resource Detectors

    • Azure App Service Resource Detector: Adds attributes for Azure App Service.
    • Azure VM Resource Detector: Adds attributes for Azure Virtual Machines.
    • ASP.NET Core Environment Resource Detector: Adds attributes from the ASP.NET Core environment configuration.

    Other Features

    • Live Metrics: Integrated support for real-time monitoring.
    • Azure Monitor Exporter: Uses Azure.Monitor.OpenTelemetry.Exporter to send data to Azure Monitor.
  3. How to use TelemetryClient with the Single Instance Pattern

    main

    To log custom telemetry, use the TelemetryClient API.

    CRITICAL: Single Instance Pattern Required In version 3.x, you must create a TelemetryConfiguration using TelemetryConfiguration.CreateDefault() (which loads from ApplicationInsights.config), then pass it to the TelemetryClient constructor.

    You must create exactly ONE TelemetryClient instance at application startup and reuse it throughout the application's lifetime.

    Creating multiple instances causes:

    • Memory leaks: Internal buffers and timers are never released.
    • Performance degradation: Each instance spawns background threads for batching.
    • Duplicate telemetry: Multiple instances may send the same data.
    • Configuration inconsistencies.
    // Recommended initialization in Global.asax.cs
    protected void Application_Start()
    {
        var configuration = TelemetryConfiguration.CreateDefault();
        TelemetryClient = new TelemetryClient(configuration);
    }
  4. Track page views (Server-side workaround)

    main

    Note: TrackPageView() is not available in version 3.x of the SDK.

    For server-side tracking of page views, you should use TrackEvent() or TrackRequest() instead. For client-side page view tracking, use the Application Insights JavaScript SDK.

    // Track page view as an event
    telemetryClient.TrackEvent("PageView", new Dictionary<string, string>
    {
        { "PageName", "ProductDetails" },
        { "Url", "https://myapp.com/products/12345" },
        { "ProductId", "12345" },
        { "Category", "Electronics" }
    });
    
    // Or track as a request for page loads
    telemetryClient.TrackRequest(
        name: "GET /products/12345",
        startTime: DateTimeOffset.UtcNow,
        duration: TimeSpan.FromMilliseconds(150),
        responseCode: "200",
        success: true);
  5. Configure telemetry settings with TelemetryConfiguration

    main

    Use TelemetryConfiguration to manage the behavior and settings of your telemetry pipeline. Key configuration areas include:

    • Connection String: Specifying the destination resource.
    • Sampling settings: Controlling the volume of telemetry sent to manage costs and performance.
    • AAD authentication: Configuring Azure Active Directory authentication.
    • Offline storage: Managing how telemetry is stored when the application is disconnected from the service.

    Settings can be applied via code or through configuration files like applicationinsights.config (and upcoming support for appsettings.json).

  6. Understand the SDK Version field for troubleshooting

    main

    The ai.internal.sdkVersion tag is a field included in every telemetry item. It identifies the specific SDK that collected that particular piece of telemetry. This is primarily used for troubleshooting to determine which version of an SDK was active when an event or metric was recorded.

    To implement this in your own telemetry, you must include the SDK name and version within the tags collection using the key ai.internal.sdkVersion.

    {
      "tags": {
        "ai.internal.sdkVersion": "dotnet:2.0.0"
      }
    }
  7. SQL Client Instrumentation compatibility and usage notes

    main

    Compatibility

    • Supports both System.Data.SqlClient and Microsoft.Data.SqlClient.
    • Classic ASP.NET applications include this instrumentation by default.

    Usage Guidance

    • EF Core Users: If you are using EF Core with SQL Server, EF Core instrumentation captures the same spans. Use this specific SQL Client instrumentation for raw SqlCommand or SqlConnection calls.
    • Security Warning: Setting SetDbStatementForText = true captures raw SQL commands, which may contain sensitive information or PII (Personally Identifiable Information).
  8. Create nested activities and trace hierarchies

    main

    Activities automatically form a parent-child hierarchy based on the execution flow. When an activity is started within the scope of another, it becomes a child, linked via TraceId and ParentId. This creates a trace tree in Application Insights, allowing you to visualize the flow of a single operation through multiple sub-tasks and external calls.

    public async Task ProcessOrderAsync(string orderId)
    {
        using var orderActivity = MyAppTracing.Source.StartActivity("ProcessOrder", ActivityKind.Internal);
        orderActivity?.SetTag("order.id", orderId);
    
        // This activity becomes a child of ProcessOrder
        await ValidateOrderAsync(orderId);
    
        // This activity also becomes a child of ProcessOrder
        await ChargePaymentAsync(orderId);
    
        orderActivity?.SetStatus(ActivityStatusCode.Ok);
    }
    
    private async Task ValidateOrderAsync(string orderId)
    {
        using var activity = MyAppTracing.Source.StartActivity("ValidateOrder", ActivityKind.Internal);
        // ... validation logic ...
        activity?.SetStatus(ActivityStatusCode.Ok);
    }
    
    private async Task ChargePaymentAsync(string orderId)
    {
        using var activity = MyAppTracing.Source.StartActivity("ChargePayment", ActivityKind.Client);
        activity?.SetTag("payment.provider", "stripe");
        // ... payment call ...
        activity?.SetStatus(ActivityStatusCode.Ok);
    }
  9. Compare Application Insights for ASP.NET Core vs Worker Services

    main

    When choosing between the ASP.NET Core and Worker Service SDKs, note the following differences:

    FeatureASP.NET CoreWorker Service
    Extension MethodAddApplicationInsightsTelemetry()AddApplicationInsightsTelemetryWorkerService()
    Host TypeWebApplicationHost
    ASP.NET Core Instrumentation✅ Included (HTTP requests)❌ Not included
    HTTP Client Instrumentation✅ Included✅ Included
    SQL Client Instrumentation✅ Included✅ Included
    Live Metrics✅ Supported✅ Supported
    Custom TelemetryTelemetryClient + OpenTelemetry APIsTelemetryClient + OpenTelemetry APIs
  10. Manage Telemetry Modules in 3.x

    main

    In 3.x, many ITelemetryModule implementations are no longer registered manually via AddApplicationInsightsTelemetry(). Their functionality is now handled internally, often via OpenTelemetry instrumentation. To control these features, use the corresponding toggles in ApplicationInsightsServiceOptions.

    Feature3.x StatusConfiguration Property
    Request TrackingInternal (OpenTelemetry)EnableRequestTrackingTelemetryModule
    Dependency TrackingInternal (OpenTelemetry)EnableDependencyTrackingTelemetryModule
    Performance CountersInternalEnablePerformanceCounterCollectionModule
    Live MetricsInternalEnableQuickPulseMetricStream
    Diagnostics/HeartbeatInternalN/A (Removed)
    Event Counter CollectionDiscontinuedN/A
  11. Adhere to OpenTelemetry naming conventions for metrics

    main

    In 3.x, Application Insights uses OpenTelemetry internally. All metric identifiers must follow the OpenTelemetry Instrument Name Syntax.

    Requirements:

    • Must not be null or empty.
    • Must be case-insensitive, ASCII strings.
    • The first character must be an alphabetic character (A-Z or a-z).
    • Subsequent characters must be alphanumeric (A-Z, a-z, 0-9), _, ., -, or /.
    • Maximum length of 255 characters.

    Affected Methods:

    • TrackMetric(string name, double value, ...): The name parameter.
    • GetMetric(string metricId, ...): The metricId parameter.
    • MetricIdentifier(string metricNamespace, string metricId, ...): Both metricNamespace and metricId parameters.

    Note: If your existing metric names contain characters like spaces, $, or #, you must rename them before migrating to 3.x.