ASP.NET Web サイトに Application Insights を構成する

この手順では、Azure Monitor サービスの Application Insights 機能にテレメトリを送信するように、ASP.NET Web アプリを構成します。 これは、オンプレミスの独自の IIS サーバーまたはクラウドでホストされている ASP.NET アプリに対して機能します。

Note

以下のドキュメントは、Application Insights クラシック API に関するものです。 Application Insights の長期的な計画は、OpenTelemetry を使用してデータを収集することです。 詳しくは、「.NET、Node.js、Python、Java アプリケーション用の Azure Monitor OpenTelemetry を有効にする」をご覧ください。

Note

インストルメンテーション キーのインジェストのサポートは、2025 年 3 月 31 日に終了します。 インストルメンテーション キーのインジェストは引き続き機能しますが、この機能の更新プログラムやサポートは提供されなくなります。 接続文字列に移行することで、新機能をご利用いただけます。

前提条件

ASP.NET Web サイトに Application Insights を追加するうえで必要なことは次のとおりです。

重要

インストルメンテーション キーに対して接続文字列をお勧めします。 新しい Azure リージョンでは、インストルメンテーション キーの代わりに接続文字列を使用する必要があります。

接続文字列により、テレメトリ データと関連付けるリソースが識別されます。 また、リソースでテレメトリの宛先として使用するエンドポイントを変更することもできます。 接続文字列をコピーし、アプリケーションのコードまたは "APPLICATIONINSIGHTS_CONNECTION_STRING" 環境変数に追加する必要があります。

基本的な ASP.NET Web アプリを作成する

  1. Visual Studio 2019 を開きます。
  2. [File]>[New]>[Project] の順に選択します。
  3. [ASP.NET Web アプリケーション (.NET Framework) C#] を選択します。
  4. プロジェクト名を入力して、[作成] を選択します。
  5. [MVC]>[作成] を選択します。

Application Insights を自動的に追加する

このセクションでは、テンプレートベースの ASP.NET Web アプリに Application Insights を自動的に追加する手順について説明します。 Visual Studio の ASP.NET Web アプリ プロジェクト内から:

  1. [プロジェクト]>[Application Insights Telemetry の追加]>[Application Insights SDK (ローカル)]>[次へ]>[完了]>[閉じる] の順に選択します。

  2. ApplicationInsights.config ファイルを開きます。

  3. 終了タグ </ApplicationInsights> の前に、自分の Application Insights リソースの接続文字列を含む行を追加します。 新しく作成された Application Insights リソースの [概要] ペインで接続文字列を見つけます。

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  4. [プロジェクト]>[NuGet パッケージの管理]>[更新] を選択します。 次に、各 Microsoft.ApplicationInsights NuGet パッケージを最新の安定版リリースに更新します。

  5. [IIS Express] を選択してアプリケーションを実行します。 基本的な ASP.NET アプリが開きます。 サイトでページを移動して閲覧すると、テレメトリが Application Insights に送信されます。

Application Insights を手動で追加する

このセクションでは、テンプレートベースの ASP.NET Web アプリに Application Insights を手動で追加する手順について説明します。 このセクションでは、ASP.NET Framework 用の標準の MVC Web アプリ テンプレートに基づく Web アプリを使用していることを前提としています。

  1. 次の NuGet パッケージとその依存関係をプロジェクトに追加します。

  2. 場合によっては、ApplicationInsights.config ファイルが自動的に作成されます。 ファイルが既に存在する場合は、手順 4 に進みます。

    自動的に作成されない場合は、自分で作成する必要があります。 ASP.NET アプリケーションのルート ディレクトリに、ApplicationInsights.configという名前の新規ファイルを作成します。

  3. 次の XML 構成を新しく作成したファイルにコピーします。

    <?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" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
          <!-- Extended list of bots:
                search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
          <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
      </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>Azure.Messaging.ServiceBus</Add>
          </IncludeDiagnosticSourceActivities>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
          <!--
          Use the following syntax here to collect additional performance counters:
    
          <Counters>
            <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
            ...
          </Counters>
    
          PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
    
          NOTE: performance counters configuration will be lost upon NuGet upgrade.
    
          The following placeholders are supported as InstanceName:
            ??APP_WIN32_PROC?? - instance name of the application process  for Win32 counters.
            ??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
            ??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
          <!--
          Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider 
          with the following syntax:
    
          <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
            <ExcludedHeartbeatProperties>
              <Add>osType</Add>
              <Add>location</Add>
              <Add>name</Add>
              <Add>offer</Add>
              <Add>platformFaultDomain</Add>
              <Add>platformUpdateDomain</Add>
              <Add>publisher</Add>
              <Add>sku</Add>
              <Add>version</Add>
              <Add>vmId</Add>
              <Add>vmSize</Add>
              <Add>subscriptionId</Add>
              <Add>resourceGroupName</Add>
              <Add>placementGroupId</Add>
              <Add>tags</Add>
              <Add>vmScaleSetName</Add>
            </ExcludedHeartbeatProperties>
          </Add>
    
          NOTE: exclusions will be lost upon upgrade.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
          <!--</Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
          <Handlers>
            <!-- 
            Add entries here to filter out additional handlers: 
    
            NOTE: handler configuration will be lost upon NuGet upgrade.
            -->
            <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
            <Add>System.Web.StaticFileHandler</Add>
            <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
            <Add>System.Web.Optimization.BundleHandler</Add>
            <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
            <Add>System.Web.Handlers.TraceHandler</Add>
            <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
            <Add>System.Web.HttpDebugHandler</Add>
          </Handlers>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
      </TelemetryModules>
      <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
      <TelemetrySinks>
        <Add Name="default">
          <TelemetryProcessors>
            <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
            <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
            <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
              <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
              <ExcludedTypes>Event</ExcludedTypes>
            </Add>
            <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
              <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
              <IncludedTypes>Event</IncludedTypes>
            </Add>
            <!--
              Adjust the include and exclude examples to specify the desired semicolon-delimited types. (Dependency, Event, Exception, PageView, Request, Trace)
            -->
          </TelemetryProcessors>
          <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
        </Add>
      </TelemetrySinks>
      <!-- 
        Learn more about Application Insights configuration with ApplicationInsights.config here: 
        http://go.microsoft.com/fwlink/?LinkID=513840
      -->
      <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    </ApplicationInsights>
    
  4. 終了タグ </ApplicationInsights> の前に、自分の Application Insights リソースの接続文字列を追加します。 新しく作成された Application Insights リソースの [概要] ペインで接続文字列を見つけることができます。

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  5. プロジェクトの ApplicationInsights.config ファイルと同じレベルに、AiHandleErrorAttribute.cs という名前の新しい C# ファイルが含まれる ErrorHandler という名前のフォルダーを作成します。 ファイルの内容は次のようになります。

    using System;
    using System.Web.Mvc;
    using Microsoft.ApplicationInsights;
    
    namespace WebApplication10.ErrorHandler //namespace will vary based on your project name
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
        public class AiHandleErrorAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
                {
                    //If customError is Off, then AI HTTPModule will report the exception
                    if (filterContext.HttpContext.IsCustomErrorEnabled)
                    {   
                        var ai = new TelemetryClient();
                        ai.TrackException(filterContext.Exception);
                    } 
                }
                base.OnException(filterContext);
            }
        }
    }
    
  6. App_Start フォルダーで FilterConfig.cs ファイルを開き、次のサンプルに一致するように変更します。

    using System.Web;
    using System.Web.Mvc;
    
    namespace WebApplication10 //Namespace will vary based on project name
    {
        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());
            }
        }
    }
    
  7. Web.config が既に更新されている場合は、この手順をスキップします。 そうでない場合は、ファイルを次のように更新します。

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      https://go.microsoft.com/fwlink/?LinkId=301880
      -->
    <configuration>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2" />
        <!-- Code added for Application Insights start -->
        <httpModules>
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
        <!-- Code added for Application Insights end -->
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
            <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
          <!-- Code added for Application Insights start -->
          <dependentAssembly>
            <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
          </dependentAssembly>
          <!-- Code added for Application Insights end -->
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <!-- Code added for Application Insights start -->
        <modules>
          <remove name="TelemetryCorrelationHttpModule" />
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler" />
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
        <!-- Code added for Application Insights end -->
      </system.webServer>
    </configuration>
    
    

これで、サーバー側アプリケーションの監視が正常に構成されました。 Web アプリを実行すると、Application Insights にテレメトリが表示され始めます。

クライアント側の監視を追加します。

前のセクションでは、サーバー側の監視を自動および手動で構成する方法に関するガイダンスを提供しました。 クライアント側の監視を追加するには、Microsoft の クライアント側 JavaScript SDK を使用します。 ページの HTML の終了タグ </head> の前に JavaScript JavaScript (Web) SDK ローダー スクリプトを追加することで、Web ページのクライアント側トランザクションを監視できます。

各 HTML ページのヘッダーに JavaScript (Web) SDK ローダー スクリプトを手動で追加することもできますが、代わりにその JavaScript (Web) SDK ローダー スクリプトをプライマリ ページに追加することをお勧めします。 このアクションにより、JavaScript (Web) JavaScript (Web) SDK ローダー スクリプトがサイトのすべてのページに挿入されます。

この記事のテンプレートベースの ASP.NET MVC アプリの場合、編集する必要があるファイルは _Layout.cshtml です。 それは、[ビュー]>[共有] の下にあります。 クライアント側の監視を追加するには、_Layout.cshtml を開き、クライアント側の JavaScript (Web) JavaScript SDK 構成に関する記事の JavaScript (Web) SDK ローダーのスクリプトベースのセットアップ手順に従います。

よく寄せられる質問

このセクションでは、一般的な質問への回答を示します。

SDK をアンインストールするにはどうすればよいですか?

Application Insights を削除するには、アプリケーション内の API から NuGet パッケージと参照を削除する必要があります。 NuGet パッケージは、Visual Studio で NuGet パッケージ マネージャーを使ってアンインストールできます。

  1. トレース コレクションが有効になっている場合は、まず、NuGet パッケージ マネージャーを使って Microsoft.ApplicationInsights.TraceListener パッケージをアンインストールします。ただし、どの依存関係も削除しないでください。
  2. NuGet パッケージ マネージャーのオプション コントロール内で NuGet パッケージ マネージャーとそのアンインストール オプションを使って、Microsoft.ApplicationInsights.Web パッケージをアンインストールして、その依存関係を削除します。
  3. Application Insights を完全に削除するには、プロジェクトに追加した API 呼び出しと共に、追加したコードまたはファイルを確認し、それらを手動で削除します。 詳細については、「Application Insights SDK を追加すると作成される内容」を参照してください。

Application Insights SDK を追加すると作成される内容

ご利用のプロジェクトに Application Insights を追加すると、ファイルが作成され、ファイルの一部にコードが追加されます。 NuGet パッケージをアンインストールするだけでは、そのファイルとコードが必ず破棄されるとは限りません。 Application Insights を完全に削除するには、プロジェクトに追加した API 呼び出しと共に、追加したコードまたはファイルを確認し、それらを手動で削除する必要があります。

Visual Studio ASP.NET プロジェクトに Application Insights Telemetry を追加すると、次のファイルが追加されます。

  • ApplicationInsights.config
  • AiHandleErrorAttribute.cs

次のコードが追加されます。

  • [自分のプロジェクトの名前].csproj

     <ApplicationInsightsResourceId>/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/Default-ApplicationInsights-EastUS/providers/microsoft.insights/components/WebApplication4</ApplicationInsightsResourceId>
    
  • Packages.config

    <packages>
    ...
    
      <package id="Microsoft.ApplicationInsights" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.Web" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.12.0" targetFramework="net472" />
      <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.12.0" targetFramework="net472" />
    
      <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.7" targetFramework="net472" />
    
      <package id="System.Buffers" version="4.4.0" targetFramework="net472" />
      <package id="System.Diagnostics.DiagnosticSource" version="4.6.0" targetFramework="net472" />
      <package id="System.Memory" version="4.5.3" targetFramework="net472" />
      <package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net472" />
      <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
    ...
    </packages>
    
  • Layout.cshtml

    プロジェクトに Layout.cshtml ファイルが含まれている場合は、次のコードが追加されます。

    <head>
    ...
        <script type = 'text/javascript' >
            var appInsights=window.appInsights||function(config)
            {
                function r(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} }
                var t = { config:config},u=document,e=window,o='script',s=u.createElement(o),i,f;for(s.src=config.url||'//az416426.vo.msecnd.net/scripts/a/ai.0.js',u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=['Event','Exception','Metric','PageView','Trace','Ajax'];i.length;)r('track'+i.pop());return r('setAuthenticatedUserContext'),r('clearAuthenticatedUserContext'),config.disableExceptionTracking||(i='onerror',r('_'+i),f=e[i],e[i]=function(config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o),s}),t
            }({
                instrumentationKey:'00000000-0000-0000-0000-000000000000'
            });
    
            window.appInsights=appInsights;
            appInsights.trackPageView();
        </script>
    ...
    </head>
    
  • ConnectedService.json

    {
      "ProviderId": "Microsoft.ApplicationInsights.ConnectedService.ConnectedServiceProvider",
      "Version": "16.0.0.0",
      "GettingStartedDocument": {
        "Uri": "https://go.microsoft.com/fwlink/?LinkID=613413"
      }
    }
    
  • FilterConfig.cs

            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());// This line was added
            }
    

トラブルシューティング

専用のトラブルシューティングに関する記事をご覧ください。

Visual Studio 2019 の現在のバージョンには、インストルメンテーション キーまたは接続文字列をユーザー シークレットに格納すると、.NET Framework ベースのアプリで壊れるという既知の問題があります。 このバグを回避するには、最終的にキーを applicationinsights.config ファイルにハードコードする必要があります。 この記事は、ユーザー シークレットを使用しないことで、この問題を完全に回避することを目的としています。

アプリケーション ホストとインジェスト サービスの間の接続をテストする

Application Insights SDK とエージェントからテレメトリが送信され、インジェスト エンドポイントへの REST 呼び出しとして取り込まれます。 Web サーバーまたはアプリケーション ホスト マシンからインジェスト サービス エンドポイントへの接続は、PowerShell の生の REST クライアントを使用するか、curl コマンドを使用してテストできます。 「Azure Monitor Application Insights でアプリケーション テレメトリが見つからない場合のトラブルシューティング」をご覧ください。

オープンソース SDK

コードを読んで協力してください。

最新の更新プログラムとバグ修正については、リリース ノートを参照してください

リリース ノート

バージョン2.12 以降の場合:.NET SDK (ASP.NET、ASP.NET Core、およびログ アダプターを含む)

Application Insights の主な機能強化は、サービスの更新に関するページでも要約しています。

次のステップ

  • 代理トランザクションを追加して、可用性監視を使用して、世界中から Web サイトが利用可能であることをテストします。
  • テレメトリ トラフィックとデータ ストレージのコストを削減するために、サンプリングを構成します。