Application Insights を利用したエラー分析&解消の手順(基礎)
はじめに
以前、公式 Docs の Quickstarts の手順で Durable Functions を作成した際の 記事 を公開しましたが、手順通りでは正しく構成することができませんでした。その際に Application Insights を利用してログを確認しながらエラーの解決に努めたのですが、これが無かったら恐らく解決できなかったと思います
インフラ担当としては Application Insights の閉域化 とかの話にいきがちで Application Insights を使って問題の分析などは行ったことがなく、、、備忘録として記事に残しておこうと思います
基本的な内容なのであまり Application Insights を利用したことが無い人向けの記事となります
本記事の立てつけ
Durable Functions アプリを作成してみよう(PowerShell編) の手順を実施して、エラーが発生したタイミングで Application Insights をどのように利用したかを本記事に纏めています
なお、以前の記事で参照している公式 Docs の Quickstarts は こちら となります
検証環境の構成図

Durable Functions の構成(簡易版)

作業の流れ
- 開発環境の準備 (VSCode)
- ローカルプロジェクトの作成
- 関数アプリの構成(PowerShell 7.4 とスタンドアロン Durable Functions SDK の使用)
- 関数の作成(オーケストレーター関数/アクティビティ関数/クライアント関数)
- Azure へサインイン
- Azure へ関数アプリをデプロイ
- Azure にプロジェクトをデプロイする
- 動作確認+エラー対応
- 関数アプリの再デプロイ
- 動作確認(再)+エラー対応(再)
- 動作確認(再再)
- 調査について他の方法も試してみた
1. 開発環境の準備 (VSCode)
1. 開発環境の準備 (VSCode) の手順を実施してください
2. ローカルプロジェクトの作成
2. ローカルプロジェクトの作成 の手順を実施してください
3. 関数アプリの構成(PowerShell 7.4 とスタンドアロン Durable Functions SDK の使用)
公式Docsの PowerShell 7.4 とスタンドアロン Durable Functions SDK を使用するように関数アプリを構成する を参照して作業を実施してください
3-1. local.settings.json の修正
以下の通りファイルを修正します(項目が存在しない場合は追記)
| 項目 | 設定値 |
|---|---|
| FUNCTIONS_WORKER_RUNTIME_VERSION | 7.4 |
| ExternalDurablePowerShellSDK | true |
私の検証環境における設定内容は以下の通りです
修正前
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME_VERSION": "7.4",
"FUNCTIONS_WORKER_RUNTIME": "powershell"
}
}
修正後
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME_VERSION": "7.4",
"FUNCTIONS_WORKER_RUNTIME": "powershell",
"ExternalDurablePowerShellSDK": "true"
}
}
3-2. requirements.psd1 の修正
以下の通りファイルを修正します(項目が存在しない場合は追記)
| 項目 | 設定値 |
|---|---|
| AzureFunctions.PowerShell.Durable.SDK | 2.* |
私の検証環境における設定内容は以下の通りです
修正前
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*'
# 'Az' = 'MAJOR_VERSION.*'
}
修正後
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*'
# 'Az' = 'MAJOR_VERSION.*'
'AzureFunctions.PowerShell.Durable.SDK' = '2.*'
}
3-3. profile.ps1 の修正
以下の通りファイルを修正します(項目が存在しない場合は追記)
| 項目 |
|---|
| Import-Module AzureFunctions.PowerShell.Durable.SDK -ErrorAction Stop |
私の検証環境における設定内容は以下の通りです
修正前
# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity
}
# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias
# You can also define functions or aliases that can be referenced in any of your PowerShell functions.
修正後
# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity
}
# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias
# You can also define functions or aliases that can be referenced in any of your PowerShell functions.
Import-Module AzureFunctions.PowerShell.Durable.SDK -ErrorAction Stop
4. 関数の作成(オーケストレーター関数/アクティビティ関数/クライアント関数)
4. 関数の作成(オーケストレーター関数/アクティビティ関数/クライアント関数) の手順を実施してください
5. Azure へサインイン
5. Azure へサインイン の手順を実施してください
6. Azure へ関数アプリをデプロイ
6-2. 関数アプリのデプロイ の手順を実施してください
7. Azure にプロジェクトをデプロイする
7. Azure にプロジェクトをデプロイする の手順を実施してください
8. 動作確認+エラー対応
8-1. 動作確認
自 PC のブラウザから HTTP トリガーの URL https://<functionappname>.azurewebsites.net/api/orchestrators/HelloOrchestratorへアクセスすると、エラーとなります

8-2. エラー内容調査
さすがに HTTP ERROR 500 だけでは情報が少なすぎるので Application Insights を利用してエラー内容の確認をしたいと思います
8-2-1. まずは概要を見てみる

クライアントからのアクセスはちゃんと Functions に届いてそう
8-2-2. 何で失敗しているか確認してみる



エラーメッセージ(全文)
Exception while executing function: Functions.HttpStart Result: Failure Type: Exception: Failed to install function app dependencies. Error: 'Managed Dependencies is not supported in Linux Consumption on Legion. Please remove all module references from requirements.psd1 and include the function app dependencies with the function app content. For more information, please see https://aka.ms/functions-powershell-include-modules.' Stack: at Microsoft.Azure.Functions.PowerShellWorker.DependencyManagement.DependencyManager.Initialize(ILogger logger) in D:\a\_work\1\s\src\DependencyManagement\DependencyManager.cs:line 129 at Microsoft.Azure.Functions.PowerShellWorker.DependencyManagement.DependencyManager.Initialize(StreamingMessage request, ILogger logger) in D:\a\_work\1\s\src\DependencyManagement\DependencyManager.cs:line 96 at Microsoft.Azure.Functions.PowerShellWorker.RequestProcessor.ProcessFuncti
メッセージを見る限り PowerShell の Managed Dependencies が Linux Consumption では未サポート ということらしい
8-2-3. エラーメッセージを分析してみる
requirements.psd1 の設定が該当しそうですが、なんのこっちゃ???という感じなので、とりあえずメッセージにある リンク にアクセスしてみます
上記リンクの内容を要約すると以下のような感じです
- マネージド依存関係機能は PowerShell モジュールを自動的にダウンロードして管理する機能
- Flex 従量課金プラン(Linux Consumption)ではサポートされていないので、代わりにカスタムモジュールを使用する必要がある
ということで、現時点で考えられる対処方法は以下の2つになるかと思いますが、1 の方で対応していきたいと思います
- マネージド依存関係機能を無効化して、カスタムモジュールを使用する
- (同一アプリのまま OS を変えるのは基本できないため)Windows の従量課金プランで Function App を作り直す
8-3. エラー内容解消
8-3-1. requirements.psd1 の修正
Azure Functions でマネージド依存関係を使用しないように、以下の設定値(追加した項目)を削除します
| 項目 | 設定値 |
|---|---|
| AzureFunctions.PowerShell.Durable.SDK | 2.* |
私の検証環境における設定内容は以下の通りです
修正前
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*'
# 'Az' = 'MAJOR_VERSION.*'
'AzureFunctions.PowerShell.Durable.SDK' = '2.*'
}
修正後
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*'
# 'Az' = 'MAJOR_VERSION.*'
}
8-3-2. カスタムモジュールの利用
モジュールを関数アプリのコンテンツに直接含めるために、Modules フォルダを作成し SDKをダウンロードします
| 設定項目 | 設定値 |
|---|---|
| ディレクトリ | C:\functions\Quickstarts_Powershell\Modules |
| SDK | AzureFunctions.PowerShell.Durable.SDK |
① Modules フォルダの作成
cd C:\functions\Quickstarts_Powershell
mkdir Modules
➁ AzureFunctions.PowerShell.Durable.SDK のダウンロード
Find-Module AzureFunctions.PowerShell.Durable.SDK
Save-Module -Name AzureFunctions.PowerShell.Durable.SDK -RequiredVersion 2.1.0 -Path .\Modules
dir Modules
8-3-3. マネージド依存関係の無効化
マネージド依存関係を無効化します
| 設定項目 | 設定値 |
|---|---|
| managedDependency | "enabled": false |
設定後の host.json の中身は以下となります
修正前
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"managedDependency": {
"enabled": true
}
}
修正後
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"managedDependency": {
"enabled": false
}
}
9. 関数アプリの再デプロイ
7. Azure にプロジェクトをデプロイする の手順を再度実施してください
10. 動作確認(再)+エラー対応(再)
10-1. 動作確認(再)
再度自 PC のブラウザから HTTP トリガーの URL https://<functionappname>.azurewebsites.net/api/orchestrators/HelloOrchestratorへアクセスすると、またエラーとなります

10-2. エラー内容調査(再)
再度 Application Insights を利用してエラー内容の確認をしたいと思います。手順は1回目と同様ですので、詳細メッセージのみを載せます

エラーメッセージ(全文)
Exception while executing function: Functions.HttpStart Result: Failure
Type:
Exception:
{
"Message": "Something went wrong while processing your request",
"ExceptionMessage": "An error occurred while communicating with Azure Storage",
"ExceptionType": "DurableTask.AzureStorage.Storage.DurableTaskStorageException",
"StackTrace": " at DurableTask.AzureStorage.Storage.ClientResponseExtensions.DecorateFailure[T](Task\u00601 responseTask) in /_/src/DurableTask.AzureStorage/Storage/ClientResponseExtensions.cs:line 46\n at DurableTask.AzureStorage.Storage.Table.CreateIfNotExistsAsync(CancellationToken cancellationToken) in /_/src/DurableTask.AzureStorage/Storage/Table.cs:line 51\n at DurableTask.AzureStorage.Partitioning.TablePartitionManager.DurableTask.AzureStorage.Partitioning.IPartitionManager.CreateLeaseStore() in /_/src/DurableTask.AzureStorage/Partitioning/TablePartitionManager.cs:line 266\n at DurableTask.AzureStorage.AzureStorageOrchestrationService.GetTaskHubCreatorTask() in /_/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:line 373\n at DurableTask.AzureStorage.AzureStorageOrchestrationService.EnsureTaskHubAsync() in /_/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:line 352\n at DurableTask.AzureStorage.AzureStorageOrchestrationService.CreateTaskOrchestrationAsync(TaskMessage creationMessage, OrchestrationStatus[] dedupeStatuses) in /_/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:line 1713\n at Microsoft.Azure.WebJobs.Extensions.DurableTask.HttpApiHandler.HandleStartOrchestratorRequestAsync(HttpRequestMessage request, String functionName, String instanceId) in /_/src/WebJobs.Extensions.DurableTask/HttpApiHandler.cs:line 911\n at Microsoft.Azure.WebJobs.Extensions.DurableTask.HttpApiHandler.HandleRequestAsync(HttpRequestMessage request) in /_/src/WebJobs.Extensions.DurableTask/HttpApiHandler.cs:line 309"
}
Stack: at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.Runspaces.Pipeline.Invoke()
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke[T](IEnumerable input, IList`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke[T]()
at Microsoft.Azure.Functions.PowerShellWorker.PowerShell.PowerShellExtensions.InvokeAndClearCommands[T](PowerShell pwsh) in D:\a\_work\1\s\src\PowerShell\PowerShellExtensions.cs:line 45
at Microsoft.Azure.Functions.PowerShellWorker.PowerShell.PowerShellManager.ExecuteUserCode(Boolean addPipelineOutput, IDictionary outputBindings) in D:\a\_work\1\s\src\PowerShell\PowerShellManager.cs:line 320
at Microsoft.Azure.Functions.PowerShellWorker.PowerShell.PowerShellManager.InvokeFunction(AzFunctionInfo functionInfo, Hashtable triggerMetadata, TraceContext traceContext, RetryContext retryContext, IList`1 inputData, FunctionInvocationPerformanceStopwatch stopwatch, OpenTelemetryInvocationContext otelContext) in D:\a\_work\1\s\src\PowerShell\PowerShellManager.cs:line 250
at Microsoft.Azure.Functions.PowerShellWorker.RequestProcessor.InvokeFunction(AzFunctionInfo functionInfo, PowerShellManager psManager, FunctionInvocationPerformanceStopwatch stopwatch, InvocationRequest invocationRequest) in D:\a\_work\1\s\src\RequestProcessor.cs:line 371
at Microsoft.Azure.Functions.PowerShellWorker.RequestProcessor.ProcessInvocationRequestImpl(StreamingMessage request, AzFunctionInfo functionInfo, PowerShellManager psManager, FunctionInvocationPerformanceStopwatch stopwatch) in D:\a\_work\1\s\src\RequestProcessor.cs:line 340
どうやら クライアント関数が Storage アカウント に Table を作成する際に失敗してそうな感じです
このメッセージだけだとなぜアクセスが失敗しているのかの原因まではわかりませんが、アクセスに失敗しているので「アクセス許可が無い」 or 「ネットワークが制限されている」あたりかなと思うのでそのあたりを中心に調査してみようと思います
10-2-1. ストレージアカウントのアクセス権の確認
QuickStarts の通り作成すると、ストレージアカウントの接続は Managed ID を利用するよう構成されるので、該当の Managed ID に Table へのアクセス権があるかを確認してみましたが Blob に対するアクセス権のみが付与されていました

ということで、Table に対するアクセス権を Managed ID に付与します(Durable Functionsでは Queue も利用するので併せて Queue に対するアクセス権も付与します)
アクセス権の付与については 6-4. Managed ID のロール割り当ての追加(Queue, Table) の手順を実施してください
10-2-2. ストレージアカウントのネットワーク制限の確認
念のため、ストレージアカウントのネットワーク制限についても確認してみました
こちらは特に制限はされてなさそうです

11. 動作確認(再再)
再度自 PC のブラウザから HTTP トリガーの URL https://<functionappname>.azurewebsites.net/api/orchestrators/HelloOrchestratorへアクセスすると、今度は問題無くアクセスできました!

12. 調査について他の方法も試してみた
今回私は主に「アプリケーションマップ」を利用してデバッグを実施しましたが、Application Insights にはそれ以外にも色々な機能が存在しています
どのような機能があるかは 公式Docs をご確認いただければと思いますが、私が試してみた機能について以下に簡単に纏めておきます
12-1. アプリケーションマップ
アプリケーション間の依存関係と全体構成を可視化できる



12-2. ライブメトリック
リアルタイムでアプリの挙動を確認できる



12-3. 障害
アプリケーション内で発生したエラーや失敗リクエストを時系列で分析できる



今回の利用方法(エラー原因の特定・修正)ではどの機能を利用しても大きな差はないですが、実際に操作してみた印象としては以下のように感じました
| 機能 | 使うタイミング |
|---|---|
| アプリケーションマップ | アプリケーション間の依存関係やパフォーマンスのボトルネックを可視化したいとき |
| ライブメトリック | デプロイ直後やテスト中にリアルタイムで動作を監視し、異常を即座に検出したいとき |
| 障害ビュー | 失敗したリクエストや例外の詳細を時系列で分析し、発生原因を特定したいとき |
まとめ
今回は Application Insights を利用した調査方法および対処方法についての手順を纏めました。今回利用したのはほんの一部の機能ではありますが Azure Function 初心者の私でもエラーの原因を特定し、解消することができました
Application Insights の利用方法に他の方が色々と記事に纏めていると思うのでより詳細が知りたい方は検索して探してみてください(デバッグだけでなく、監視、ユーザー利用状況・メトリクス分析、コード分析など色々な機能があります)
本記事の内容が Application Insights の利用を検討している方に少しでもお役にたてれば幸いです
Appendix
公式Docs
Zennの記事
Discussion