BlazorApplicationInsights 1.5.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package BlazorApplicationInsights --version 1.5.0
NuGet\Install-Package BlazorApplicationInsights -Version 1.5.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BlazorApplicationInsights" Version="1.5.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add BlazorApplicationInsights --version 1.5.0
#r "nuget: BlazorApplicationInsights, 1.5.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install BlazorApplicationInsights as a Cake Addin
#addin nuget:?package=BlazorApplicationInsights&version=1.5.0

// Install BlazorApplicationInsights as a Cake Tool
#tool nuget:?package=BlazorApplicationInsights&version=1.5.0

Demo Nuget (with prereleases) Nuget (with prereleases) alternate text is missing from this package README image

Application Insights for Blazor web applications

Install

  • Add BlazorApplicationInsights Nuget
    • dotnet add package BlazorApplicationInsights
  • Add call to Program.cs
    • builder.Services.AddBlazorApplicationInsights();
  • Add using statement to _Imports.razor
    • @using BlazorApplicationInsights;
  • Add component to App.razor
    • <ApplicationInsightsComponent />
  • Add Application Insights JS to head in index.html
    • Source
    • Set 'ld: -1' so that the page will be blocked until the JS is loaded and enter your instrumentationKey
      <script type="text/javascript">
        !function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),l.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(k)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{
        src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js",
        ld: -1,
        crossOrigin: "anonymous",
        cfg: {
            instrumentationKey: "INSTRUMENTATION_KEY",
            disableFetchTracking: false,
            enableCorsCorrelation: true,
            enableRequestHeaderTracking: true,
            enableResponseHeaderTracking: true
        }});
      </script>
      
  • Add JS Interop to the bottom of body in index.html
    <script src="_content/BlazorApplicationInsights/JsInterop.js"></script>
    

Example Project

Features

  • Automatically triggers Track Page View on route changes
  • ILoggerProvider which sends all the logs to App Insights (Wasm only)
  • Supported APIs
    • AddTelemetryInitializer
    • ClearAuthenticatedUserContext
    • Flush
    • SetAuthenticatedUserContext
    • StartTrackEvent
    • StartTrackPage
    • StopTrackEvent
    • StopTrackPage
    • TrackDependencyData
    • TrackEvent
    • TrackException
    • TrackMetric
    • TrackPageView
    • TrackPageViewPerformance
    • TrackTrace

TrackEvent

@page "/"

<button class="btn btn-primary" @onclick="TrackEvent">Track Event</button>

@code {
    [Inject] private IApplicationInsights AppInsights { get; set; }

    private async Task TrackEvent()
    {
        await AppInsights.TrackEvent("My Event");
    }
}

Set User Name

  • Edit Authentication.razor
@page "/authentication/{action}"

<RemoteAuthenticatorView Action="@Action" OnLogInSucceeded="OnLogInSucceeded" OnLogOutSucceeded="OnLogOutSucceeded" />

@code{
    [Parameter] public string Action { get; set; }

    [CascadingParameter] public Task<AuthenticationState> AuthenticationState { get; set; }

    [Inject] private IApplicationInsights AppInsights { get; set; }

    public async Task OnLogInSucceeded()
    {
        var user = (await AuthenticationState).User;

        await AppInsights.SetAuthenticatedUserContext(user.FindFirst("preferred_username")?.Value);
    }

    public async Task OnLogOutSucceeded()
    {
        await AppInsights.ClearAuthenticatedUserContext();
    }
}

Set Role and Instance

  • Edit Program.cs
public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    builder.Services.AddBlazorApplicationInsights(async applicationInsights =>
    {
        var telemetryItem = new TelemetryItem()
        {
            Tags = new Dictionary<string, object>()
            {
                { "ai.cloud.role", "SPA" },
                { "ai.cloud.roleInstance", "Blazor Wasm" },
            }
        };

        await applicationInsights.AddTelemetryInitializer(telemetryItem);
    });

    await builder.Build().RunAsync();
}

Set Instrumentation Key

  • Edit Index.html and remove instrumentationKey from cfg
<script type="text/javascript">
!function(T,l,y){ // Removed for brevity...
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", 
ld: -1,  // Set this to -1
crossOrigin: "anonymous",
cfg: {}
});
</script>
  • Edit Program.cs
public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    builder.Services.AddBlazorApplicationInsights(async applicationInsights =>
    {
        await applicationInsights.SetInstrumentationKey("YOUR_INSTRUMENTATION_KEY_GOES_HERE");
        await applicationInsights.LoadAppInsights();
    });

    await builder.Build().RunAsync();
}

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on BlazorApplicationInsights:

Package Downloads
Service.Extensions.Blazor.Logging The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

Extensions to provide consistent configurations and patterns for your service.

MP.Blazor.Library

An abstraction layer for the mongo nuget package to allow for easy service switching and unit testing without widescale code refactors.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on BlazorApplicationInsights:

Repository Stars
chunliu/AzureDesignStudio
A web app that helps you create the architecture design diagram for your Azure solutions and automatically generate IaC code from it.
Version Downloads Last updated
3.0.5 16,262 3/10/2024
3.0.4 57,654 1/14/2024
3.0.3 1,666 1/11/2024
3.0.2 13,176 12/17/2023
3.0.1 9,179 12/1/2023
3.0.0 5,076 11/25/2023
2.2.2 90,001 9/2/2023
2.2.1 13,524 8/22/2023
2.2.0 241,979 2/17/2023
2.1.0 170,659 11/22/2022
2.0.0 11,405 11/10/2022
1.6.0 264,854 1/16/2022
1.5.0 55,865 12/7/2021
1.4.0 21,817 11/4/2021
1.3.0 10,449 10/8/2021
1.2.1 49,369 8/5/2021
1.2.0 9,976 7/9/2021
1.1.2 22,588 5/5/2021
1.1.1 17,461 4/22/2021
1.1.0 2,800 4/20/2021
1.0.1 27,151 3/9/2021
1.0.0 5,873 2/17/2021
1.0.0-beta.1 179 2/15/2021
0.8.0 2,078 2/11/2021
0.7.1 33,039 12/1/2020
0.7.0 875 12/1/2020
0.6.0 964 11/24/2020
0.5.0 4,723 10/5/2020
0.4.0 949 10/4/2020
0.3.0 884 10/2/2020
0.2.0 4,440 7/17/2020
0.1.0 1,643 7/14/2020