注意事項
Azure Monitor Application Insights を利用する新規のアプリケーションやお客様には、Azure Monitor OpenTelemetry Distro をお勧めします。 Azure Monitor OpenTelemetry Distro では、Application Insights SDK と同様の機能とエクスペリエンスが提供されます。 .NET、Node.js、Python 用の移行ガイドを使用して Application Insights SDK から移行することはできますが、下位互換性を確保するために引き続きいくつかの機能を追加する取り組みを行っています。
この記事では、ASP.NET および ASP.NET Core アプリケーションの Application Insights を有効にして構成する方法について説明します。 この手順では、テレメトリを Application Insights に送信するようにアプリケーションを構成します。
Application Insights は、ASP.NET および ASP.NET Core アプリケーションから次のテレメトリを収集できます。
- リクエスト
- 依存関係
- 例外
- 性能カウンター
- トレース (ログ)
- ハートビート
- カスタム イベントとメトリック (手動インストルメンテーションが必要)
- ページ ビュー (Web ページには JavaScript SDK が必要)
- 可用性テスト (可用性テストを手動で設定する必要があります)
サポートされているシナリオ
メモ
Application Insights SDK for ASP.NET Core では、実行されている場所や方法に関係なく、アプリケーションを監視できます。 アプリケーションが実行されていて、Azure へのネットワーク接続がある場合は、テレメトリを収集することができます。 Application Insights の監視は、.NET Core がサポートされているすべての場所でサポートされます。
サポートされています | ASP.NET | ASP.NET Core |
---|---|---|
オペレーティング システム | ウィンドウズ | Windows、Linux、または Mac |
ホスティング方法 | インプロセス (IIS または IIS Express) | プロセス内またはプロセス外 |
デプロイ方法 | Web デプロイ、MSI、または手動ファイルコピー | フレームワーク依存または自己完結型 |
ウェブサーバー | インターネット インフォメーション サービス (IIS) | インターネット インフォメーション サーバー (IIS) または Kestrel |
ホスティング プラットフォーム | Azure App Service (Windows)、Azure Virtual Machines、またはオンプレミス サーバー | Azure App Service、Azure Virtual Machines、Docker、Azure Kubernetes Service (AKS) の Web Apps 機能 |
.NET バージョン | .NET Framework 4.6.1 以降 | 正式に サポートされているすべての .NET バージョン (プレビュー段階ではない) |
IDE | Visual Studio | Visual Studio、Visual Studio Code、またはコマンド ライン |
前提条件
- Azure サブスクリプション。 まだお持ちでない場合は、 無料の Azure アカウントを作成します。
- Application Insights ワークスペース ベースのリソース。
- 機能している Web アプリケーション。 まだお持ちでない場合は、「 基本的な Web アプリを作成する」を参照してください。
- 次のワークロードを備えた最新バージョンの Visual Studio :
- ASP.NET および Web の開発
- Azure の開発
基本的な Web アプリを作成する
MVC アプリケーションの例を使います。 Worker サービスを使用している場合は、ワーカー サービス アプリケーション向け Application Insights に関する手順を使用します。
- Visual Studio を開きます。
- [ 新しいプロジェクトの作成] を選択します。
- C#ASP.NET Web アプリケーション (.NET Framework) を選択し、[次へ] を選択します。
- プロジェクト名を入力し、[作成] を選択します。
- [MVC] を選択し、[作成] を選択します。
Application Insights を自動的に追加する (Visual Studio)
このセクションでは、テンプレート ベースの Web アプリに Application Insights を自動的に追加する方法について説明します。
メモ
ASP.NET アプリケーションにスタンドアロン ILogger プロバイダーを使用する場合は、 Microsoft.Extensions.Logging.ApplicationInsight を使用します。
Visual Studio の ASP.NET Web アプリ プロジェクト内から:
[プロジェクト]>[Application Insights Telemetry の追加]>[Application Insights SDK (ローカル)]>[次へ]>[完了]>[閉じる] の順に選択します。
ApplicationInsights.config ファイルを開きます。
終了タグ
</ApplicationInsights>
の前に、自分の Application Insights リソースの接続文字列を含む行を追加します。 新しく作成された Application Insights リソースの [概要] ペインで接続文字列を見つけます。<ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
[プロジェクト]>[NuGet パッケージの管理]>[更新] を選択します。 次に、各
Microsoft.ApplicationInsights
NuGet パッケージを最新の安定版リリースに更新します。[IIS Express] を選択してアプリケーションを実行します。 基本的な ASP.NET アプリが開きます。 サイトでページを移動して閲覧すると、テレメトリが Application Insights に送信されます。
Application Insights を手動で追加する (Visual Studio を使用しない)
このセクションでは、テンプレート ベースの Web アプリに Application Insights を手動で追加する方法について説明します。
次の NuGet パッケージとその依存関係をプロジェクトに追加します。
場合によっては、ApplicationInsights.config ファイルが自動的に作成されます。 ファイルが既に存在する場合は、手順 4 に進みます。
ない場合は、自分で作成してください。 ASP.NET アプリケーションのルート ディレクトリに、ApplicationInsights.configという名前の新規ファイルを作成します。
次の 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 the connection string from your Application Insights resource</ConnectionString> </ApplicationInsights>
接続文字列を追加します。このためには、次の 2 つの方法があります。
(推奨) 構成で接続文字列を設定します。
</ApplicationInsights>
で、終了タグ の前に Application Insights リソースの接続文字列を追加します。 新しく作成された Application Insights リソースの [概要] ペインで接続文字列を見つけることができます。<ConnectionString>Copy the connection string from your Application Insights resource</ConnectionString>
コードで接続文字列を設定します。
program.cs クラスに接続文字列を指定します。
var configuration = new TelemetryConfiguration { ConnectionString = "Copy the connection string from your Application Insights resource" };
プロジェクトの 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); } } }
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()); } } }
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=\"Web\" /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 に表示されるようになったことがわかります。
アプリケーションを実行する
アプリケーションを実行し、それに対して要求を行います。 これで Application Insights にテレメトリが送られるはずです。 Application Insights SDK によって、次のテレメトリと共に、アプリケーションへの受信 Web 要求が自動的に収集されます。
ライブ メトリック
Live Metrics を使用すると、Application Insights を使用したアプリケーションの監視が正しく構成されているかどうかをすばやく確認できます。 テレメトリが Azure portal 内に表示されるまで数分かかることがありますが、[ライブ メトリック] ペインには、実行中のプロセスの CPU 使用率がほぼリアルタイムで表示されます。 また、要求、依存関係、トレースなどの他のテレメトリも表示できます。
メモ
.NET アプリケーションの推奨される手順に従ってオンボードした場合、Live Metrics は既定で有効になります。
任意の .NET アプリケーションのコードを使用して Live Metrics を有効にする
Live Metrics を手動で構成するには:
NuGet パッケージ Microsoft.ApplicationInsights.PerfCounterCollector をインストールします。
次のサンプル コンソール アプリ コードは、Live Metrics の設定方法を示しています。
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using System;
using System.Threading.Tasks;
namespace LiveMetricsDemo
{
class Program
{
static void Main(string[] args)
{
// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.InstrumentationKey = "INSTRUMENTATION-KEY-HERE";
QuickPulseTelemetryProcessor quickPulseProcessor = null;
config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
// Secure the control channel.
// This is optional, but recommended.
quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
quickPulseModule.Initialize(config);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
// Create a TelemetryClient instance. It is important
// to use the same TelemetryConfiguration here as the one
// used to set up live metrics.
TelemetryClient client = new TelemetryClient(config);
// This sample runs indefinitely. Replace with actual application logic.
while (true)
{
// Send dependency and request telemetry.
// These will be shown in live metrics.
// CPU/Memory Performance counter is also shown
// automatically without any additional steps.
client.TrackDependency("My dependency", "target", "http://sample",
DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
client.TrackRequest("My Request", DateTimeOffset.Now,
TimeSpan.FromMilliseconds(230), "200", true);
Task.Delay(1000).Wait();
}
}
}
}
ILogger のログ記録
既定の構成では、ILogger
Warning
ログ以上の重大度のログが収集されます。 詳細については、「ILogger logs コレクションをカスタマイズする方法」を参照してください。
依存関係
自動追跡された依存関係
.NET と .NET Core 向けの Application Insights SDK には DependencyTrackingTelemetryModule
が付属しています。これは、依存関係を自動的に収集するテレメトリ モジュールです。 モジュール DependencyTrackingTelemetryModule
は Microsoft.ApplicationInsights.DependencyCollector NuGet パッケージとして出荷され、 Microsoft.ApplicationInsights.Web
NuGet パッケージまたは Microsoft.ApplicationInsights.AspNetCore
NuGet パッケージを使用すると自動的に取り込まれます。
DependencyTrackingTelemetryModule
では現在のところ、次の依存関係が自動的に追跡されます。
依存関係 | 詳細 |
---|---|
HTTP/HTTPS | ローカルまたはリモートの http/https 呼び出し。 |
WCF の呼び出し | HTTP ベースのバインディングを使用する場合にのみ自動追跡されます。 |
SQL |
SqlClient で行われる呼び出し。 SQL クエリのキャプチャについては、「詳細な SQL 追跡で完全な SQL クエリを取得する」を参照してください。 |
Azure Blob Storage、Table Storage、または Queue Storage | Azure Storage クライアントで行われた呼び出し。 |
Azure Event Hubs クライアント SDK | 最新のパッケージを使用します: https://nuget.org/packages/Azure.Messaging.EventHubs。 |
Azure Service Bus クライアント SDK | 最新のパッケージを使用します: https://nuget.org/packages/Azure.Messaging.ServiceBus。 |
Azure Cosmos DB | HTTP/HTTPS が使用されている場合は、自動的に追跡されます。 TCP を使用した直接モードでの操作のトレースは、プレビュー パッケージ >= 3.33.0-preview を使用して自動的にキャプチャされます。 詳細については、ドキュメントを参照してください。 |
依存関係が自動収集されない場合でも、TrackDependency 呼び出しを使えば手動で追跡することができます。
依存関係の追跡のしくみの詳細については、「 Application Insights での依存関係の追跡」を参照してください。
コンソール アプリで自動依存関係追跡を設定する
.NET コンソール アプリから依存関係を自動的に追跡するには、NuGet パッケージ Microsoft.ApplicationInsights.DependencyCollector
をインストールし、DependencyTrackingTelemetryModule
を初期化します:
DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();
depModule.Initialize(TelemetryConfiguration.Active);
依存関係を手動で追跡する
次の例では、依存関係が自動的に収集されず、手動追跡が必要になります。
- Azure Cosmos DB は、HTTP/HTTPS が使用されている場合にのみ、自動的に追跡されます。
2.22.0-Beta1
より古い SDK バージョンの Application Insights では、TCP モードは自動的にキャプチャされません。 - Redis
SDK で自動追跡されない依存関係については、標準の自動収集モジュールで使用される TrackDependency API を利用し、手動で追跡できます。
例
自分で記述していないアセンブリを使ってコードを作成する場合、それに対するすべての呼び出しの時間を計ることができます。 このシナリオでは、それが応答時間にどのように貢献するかを知ることができます。
このデータを Application Insights 内の依存関係グラフに表示するには、データを TrackDependency
を使用して送信します:
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
// making dependency call
success = dependency.Call();
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("myDependencyType", "myDependencyCall", "myDependencyData", startTime, timer.Elapsed, success);
}
あるいは、TelemetryClient
から拡張メソッドの StartOperation
と StopOperation
が提供されます。出力方向の依存関係の追跡で確認できるように、それを利用して依存関係を手動追跡できます。
標準の依存関係追跡モジュールを無効にする
詳細な SQL 追跡で完全な SQL クエリを取得する
SQL 呼び出しの場合、サーバーとデータベースの名前が常に収集され、収集された DependencyTelemetry
の名前として保存されます。 「データ」という名称の別のフィールドがあります。これに完全な SQL クエリ テキストを含めることができます。
メモ
Azure Functions には、SQL テキスト コレクションを有効にするための別の設定が必要です。 詳細については、「SQL クエリ コレクションを有効にする」を参照してください。
ASP.NET アプリケーションの場合は、バイト コード インストルメンテーションの支援により、完全な SQL クエリ テキストが収集されます。これには、インストルメンテーション エンジン、または System.Data.SqlClient ライブラリではなく Microsoft.Data.SqlClient NuGet パッケージの使用が要求されます。 完全な SQL クエリの収集を有効にするためのプラットフォーム固有の手順を、次の表に示します。
プラットホーム | 完全な SQL クエリを取得するために必要な手順 |
---|---|
Azure App Service の Web アプリ | Web アプリのコントロール パネルで Application Insights ペインを開き、SQL コマンドを .NET の下で有効にします。 |
IIS Server (Azure VM やオンプレミスなど) | Microsoft.Data.SqlClient NuGet パッケージを使用するか、Application Insights Agent PowerShell モジュールを使用して、インストルメンテーション エンジンをインストールして IIS を再起動します。 |
Azure Cloud Services |
StatusMonitor をインストールするスタートアップ タスクを追加します。 ASP.NET または ASP.NET Core アプリケーション用の NuGet パッケージをインストールすることで、ビルド時にアプリを ApplicationInsights SDK にオンボードする必要があります。 |
IIS Express | Microsoft.Data.SqlClient NuGet パッケージを使用します。 |
Azure App Service での WebJobs | Microsoft.Data.SqlClient NuGet パッケージを使用します。 |
前述のプラットフォーム固有の手順に加えて、次のコードで ファイルを変更することで、"SQL コマンドの収集の有効化も明示的に選択する" 必要があります。applicationInsights.config
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
</Add>
前述の例では、インストルメンテーション エンジンが正しくインストールされていることを検証する適切な方法は、収集された DependencyTelemetry
の SDK バージョンが rddp
であることを確認することです。
rdddsd
または rddf
を使用することは、DiagnosticSource
または EventSource
コールバックを介して依存関係が収集されること、そのため、完全な SQL クエリはキャプチャされないことを示します。
性能カウンター
ASP.NET はパフォーマンス カウンターを完全にサポートしますが、ASP.NET Core では SDK のバージョンとホスティング環境に応じて制限付きのサポートが提供されます。 詳細については、「Application Insights の .NET のカウンター」を参照してください。
イベント カウンター
Application Insights では、 EventCounterCollectionModule
を使用した EventCounters の収集がサポートされています。これは、ASP.NET Core に対して既定で有効になっています。 収集するカウンターの一覧を構成する方法については、「 Application Insights の .NET のカウンター」を参照してください。
HTTP を使用してデータを強化する
var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;
if (requestTelemetry != null)
{
requestTelemetry.Properties["myProp"] = "someData";
}
Application Insights SDK を構成する
Application Insights SDK for ASP.NET と ASP.NET Core をカスタマイズして、既定の構成を変更できます。
ASP.NET アプリケーション用に Application Insights SDK を構成する方法については、「 ApplicationInsights.config または .xmlを使用して Application Insights SDK を構成 する」を参照してください。
サンプリング
ASP.NET アプリケーションのサンプリングを構成する方法については、「 Application Insights でのサンプリング」を参照してください。
テレメトリ初期化子
テレメトリを追加情報で強化したり、標準のテレメトリ モジュールによって設定されたテレメトリ プロパティをオーバーライドしたりするには、テレメトリ初期化子を使用します。
ASP.NET アプリケーションでテレメトリ初期化子を使用する方法については、「 Application Insights SDK でのテレメトリのフィルター処理と前処理」を参照してください。
テレメトリ プロセッサ
ASP.NET アプリケーションでテレメトリ プロセッサを使用する方法については、「 Application Insights SDK でのテレメトリのフィルター処理と前処理」を参照してください。
既定の TelemetryModules を構成または削除する
Application Insights では、ユーザーによる手動の追跡を必要とせずに特定のワークロードに関するテレメトリが自動収集されます。
既定では、次の自動収集モジュールが有効になります。 これらのモジュールでは、自動的にテレメトリが収集されます。 それらを無効にするか構成して、既定の動作を変更できます。
-
RequestTrackingTelemetryModule
: 受信 Web 要求から RequestTelemetry を収集します。 -
DependencyTrackingTelemetryModule
: 送信 HTTP 呼び出しと SQL 呼び出しから DependencyTelemetry を収集します。 -
PerformanceCollectorModule
: Windows PerformanceCounters を収集します。 -
QuickPulseTelemetryModule
: [ライブ メトリック] ペイン内に表示するテレメトリを収集します。 -
AppServicesHeartbeatTelemetryModule
: アプリケーションがホストされる App Service 環境について、(カスタム メトリックとして送信される) ハート ビートを収集します。 -
AzureInstanceMetadataTelemetryModule
: アプリケーションがホストされる Azure VM 環境について、(カスタム メトリックとして送信される) ハート ビートを収集します。 -
EventCounterCollectionModule
: EventCounters を収集します。 このモジュールは新機能であり、SDK バージョン 2.8.0 以降で使用できます。
ASP.NET アプリケーションのテレメトリ モジュールを構成または削除する方法については、「 ApplicationInsights.config または .xmlを使用して Application Insights SDK を構成 する」を参照してください。
クライアント側の監視を追加します。
前のセクションでは、サーバー側の監視を自動および手動で構成する方法に関するガイダンスを提供しました。 クライアント側の監視を追加するには、Microsoft の クライアント側 JavaScript SDK を使用します。 ページの HTML の終了タグ の前に </head>
を追加すると、任意の 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 ローダーのスクリプトベースのセットアップ手順に従います。
トラブルシューティング
専用のトラブルシューティングに関する記事をご覧ください。
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 の主な機能強化は、サービスの更新に関するページでも要約しています。
次のステップ
- サポートされているバージョンの Application Insights SDK を実行していることを確認します。
- 代理トランザクションを追加して、可用性監視を使用して、世界中から Web サイトが利用可能であることをテストします。
- テレメトリ トラフィックとデータ ストレージのコストを削減するために、サンプリングを構成します。
- ユーザー フローの探索: ユーザーがアプリ内をどのように移動しているかを把握します。
- スナップショット コレクションを構成して、例外がスローされたときのソース コードと変数の状態を確認します。
- API を使用して、アプリのパフォーマンスと使用の詳細を表示するための独自のイベントとメトリックスを送信します。
- よく寄せられる質問 (FAQ) を確認するには、「 Applications Insights for ASP.NET FAQ」を参照してください。