次の方法で共有


.NET を使用した Application Insights のログ

この記事では、Microsoft.Extensions.Logging.ApplicationInsights プロバイダー パッケージを使用して .NET アプリの Application Insights でログをキャプチャする方法について説明します。 このプロバイダーを使用する場合は、Application Insights ツールを使ってクエリを実行し、ログを分析できます。

注意事項

Azure Monitor Application Insights を利用する新規のアプリケーションやお客様には、Azure Monitor OpenTelemetry Distro をお勧めします。 Azure Monitor OpenTelemetry Distro では、Application Insights SDK と同様の機能とエクスペリエンスが提供されます。 .NETNode.jsPython 用の移行ガイドを使用して Application Insights SDK から移行することはできますが、下位互換性を確保するために引き続きいくつかの機能を追加する取り組みを行っています。

ヒント

ASP.NET Core アプリケーション

ASP.NET Core アプリケーションに Application Insights ログを追加するには:

  1. Microsoft.Extensions.Logging.ApplicationInsightsをインストールします。

  2. ApplicationInsightsLoggerProvider を追加します。

using Microsoft.Extensions.Logging.ApplicationInsights;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Logging.AddApplicationInsights(
        configureTelemetryConfiguration: (config) => 
            config.ConnectionString = builder.Configuration.GetConnectionString("APPLICATIONINSIGHTS_CONNECTION_STRING"),
            configureApplicationInsightsLoggerOptions: (options) => { }
    );

builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("your-category", LogLevel.Trace);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

NuGet パッケージがインストールされ、プロバイダーが依存関係の挿入に登録されると、アプリはログを記録する準備が整います。 コンストラクターの挿入では、ILogger またはジェネリック型の代替である ILogger<TCategoryName> のいずれかが必要になります。 これらの実装が解決されると、ApplicationInsightsLoggerProvider によってこれらが提供されるようになります。 ログされたメッセージや例外は、Application Insights に送信されます。

たとえば、次のコントローラーの例を考えてみましょう。

public class ValuesController : ControllerBase
{
    private readonly ILogger _logger;

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

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        _logger.LogWarning("An example of a Warning trace..");
        _logger.LogError("An example of an Error level message");

        return new string[] { "value1", "value2" };
    }
}

詳細については、ASP.NET Coreでのログに関するページ、および「ILogger ログからはどのような種類の Application Insights テレメトリが生成されますか? Application Insights ではどこで ILogger ログを見ることができますか?」を参照してください。

コンソール アプリケーション

Application Insights ログ記録をコンソール アプリケーションに追加するには、最初に 以下のNuGet パッケージをインストールします:

次の例では、Microsoft.Extensions.Logging.ApplicationInsights パッケージを使用し、コンソール アプリケーションの既定の動作を示しています。 Microsoft.Extensions.Logging.ApplicationInsights パッケージは、コンソール アプリケーションで、または完全な機能セット (メトリック、分散トレース、サンプリング、テレメトリ初期化子など) を使用せずに Application Insights の最小限の実装が必要なときに常に、使用する必要があります。

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using var channel = new InMemoryChannel();

try
{
    IServiceCollection services = new ServiceCollection();
    services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
    services.AddLogging(builder =>
    {
        // Only Application Insights is registered as a logger provider
        builder.AddApplicationInsights(
            configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
            configureApplicationInsightsLoggerOptions: (options) => { }
        );
    });

    IServiceProvider serviceProvider = services.BuildServiceProvider();
    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

    logger.LogInformation("Logger is working...");
}
finally
{
    // Explicitly call Flush() followed by Delay, as required in console apps.
    // This ensures that even if the application terminates, telemetry is sent to the back end.
    channel.Flush();

    await Task.Delay(TimeSpan.FromMilliseconds(1000));
}

詳細については、「ILogger ログからはどのような種類の Application Insights テレメトリが生成されますか? Application Insights ではどこで ILogger ログを見ることができますか?」を参照してください。

ログのスコープ

ApplicationInsightsLoggingProvider では、ログ スコープがサポートされます。 スコープは既定で有効になっています。

スコープの型が IReadOnlyCollection<KeyValuePair<string,object>> の場合、コレクション内のキーと値の各ペアが、カスタム プロパティとして、Application Insights テレメトリに追加されます。 次の例では、ログは TraceTelemetry としてキャプチャされ、プロパティに ("MyKey", "MyValue") が含まれています。

using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" }))
{
    _logger.LogError("An example of an Error level message");
}

他の型がスコープとして使用される場合は、Application Insights テレメトリのプロパティ Scope に格納されます。 次の例では、TraceTelemetry に、スコープを含む Scope という名前のプロパティが設定されます。

using (_logger.BeginScope("hello scope"))
{
    _logger.LogError("An example of an Error level message");
}

次のステップ