다음을 통해 공유


.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와 유사한 기능과 환경을 제공합니다. .NET, Node.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");
}

다음 단계