LoginSignup
9
5

More than 3 years have passed since last update.

ASP.NET Core で Application Insights を手動で構成する手順

Posted at

以下のページのサマリ
Application Insights for ASP.NET Core アプリケーション

NuGet の追加

以下のパッケージを追加します

  • Microsoft.ApplicationInsights.AspNetCore

Startup.cs への AppInsights 有効化の処理の追加

以下のコードを追加

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    services.AddRazorPages();
}

この時点で実際の Azure には行かないけどローカルでデバッグ実行すると Visual Studio で確認できるようになります。

image.png

ILogger 用のログレベルの調整

デフォルトで警告以上が対象なので、もうちょっと詳細な情報が欲しい場合は appsettings.json の Logging の下に ApplicationInsights を追加してログレベルを構成できます。
こんな感じになります。

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  },
  "AllowedHosts": "*"
}

例えば今回は Razor Pages のプロジェクトを作ったので Index.cshtlm.cs の OnGet で以下のようなログを仕込むと…

Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WebApplication10.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            _logger.LogInformation("★(^_-)-☆★");
        }
    }
}

こんな風に出てきます。

image.png

Azure にデプロイしたときは Azure の Application Insights に行くようにしたい

Application Insights を作成すると接続文字列が取得できます。

image.png

接続文字列を、APPLICATIONINSIGHTS_CONNECTION_STRING 環境変数に設定します。Azure Web Appsだと構成のアプリケーション設定で設定しましょう。

image.png

アプリをデプロイして実行するとログが Application Insights に出るようになります。

image.png

以下のようにクエリも出来ます。ルールを設定すれば指定の条件を満たしたときにメールなどで通知することも出来ます。

image.png

まとめ

とりあえず必要最低限の手順はこんな感じっぽいです。

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5