.NET을 사용한 Application Insights 로깅

이 문서에서는 Microsoft.Extensions.Logging.ApplicationInsights 공급자 패키지를 사용하여 .NET 앱에서 Application Insights로 로그를 캡처하는 방법을 알아봅니다. 이 공급자를 사용하는 경우 Application Insights 도구를 사용하여 로그를 쿼리 및 분석할 수 있습니다.

참고 항목

다음 설명서는 Application Insights 클래식 API를 사용합니다. Application Insights에 대한 장기 플랜은 OpenTelemetry를 사용하여 데이터를 수집하는 것입니다. 자세한 내용은 .NET, Node.js, Python 및 Java 애플리케이션에 대해 Azure Monitor OpenTelemetry 사용을 참조하세요.

참고 항목

로깅과 함께 Application Insights 원격 분석의 전체 범위를 구현하려면 ASP.NET 웹 사이트에 대한 Application Insights 구성 또는 ASP.NET Core 애플리케이션에 대한 Application Insights를 참조하세요.

백그라운드 서비스에 Application Insights를 사용하도록 설정하는 데 사용되는 Microsoft.ApplicationInsights.WorkerService NuGet 패키지는 여기서 다루지 않습니다. 자세한 내용은 작업자 서비스 앱에 대한 Application Insights를 참조하세요.

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");
    }

자주 묻는 질문

ILogger 로그에서는 어떤 Application Insights 원격 분석 유형을 생성하나요? Application Insights의 어디에서 ILogger 로그를 볼 수 있나요?

ApplicationInsightsLoggerProviderILogger 로그를 캡처하여 TraceTelemetry를 만듭니다. Exception 개체가 ILoggerLog 메서드에 전달되는 경우 TraceTelemetry 대신 ExceptionTelemetry가 생성됩니다.

ILogger 원격 분석 보기

Azure Portal에서 다음을 수행합니다.

  1. Azure Portal로 이동한 후 Application Insights 리소스에 액세스합니다.
  2. Application Insights 내에서 "로그" 섹션을 클릭합니다.
  3. KQL(Kusto 쿼리 언어)을 사용하여 일반적으로 traces 테이블에 저장되는 ILogger 메시지를 쿼리합니다.
    • 쿼리 예: traces | where message contains "YourSearchTerm".
  4. 심각도, 시간 범위 또는 특정 메시지 콘텐츠를 사용하여 ILogger 데이터를 필터링하도록 쿼리를 구체화합니다.

Visual Studio(로컬 디버거)에서 다음을 수행합니다.

  1. Visual Studio의 디버그 모드에서 애플리케이션을 시작합니다.
  2. 애플리케이션이 실행되는 동안 "진단 도구" 창을 엽니다.
  3. "이벤트" 탭에서 ILogger 로그는 다른 원격 분석 데이터와 함께 표시됩니다.
  4. "진단 도구" 창에서 검색 및 필터 기능을 활용하여 특정 ILogger 메시지를 찾습니다.

항상 TraceTelemetry를 보내려면 다음 코드 조각을 사용합니다.

builder.AddApplicationInsights(
    options => options.TrackExceptionsAsExceptionTelemetry = false);

일부 ILogger 로그가 다른 속성과 같은 속성을 포함하지 않는 이유는 무엇인가요?

Application Insights는 다른 모든 원격 분석에 사용되는 것과 동일한 TelemetryConfiguration 정보를 사용하여 ILogger 로그를 캡처하고 전송합니다. 그러나 예외가 있습니다. 기본적으로, Program.cs 또는 Startup.cs에서 로그하는 경우에는 TelemetryConfiguration이 완전하게 설정되지 않습니다. 이러한 위치의 로그에는 기본 구성이 없으므로 모든 TelemetryInitializer인스턴스와 TelemetryProcessor 인스턴스를 실행하지는 않습니다.

독립 실행형 패키지 Microsoft.Extensions.Logging.ApplicationInsights를 사용하고 있고, 추가 사용자 지정 원격 분석을 수동으로 로그하고 싶습니다. 방법을 알려주세요.

독립 실행형 패키지를 사용하는 경우TelemetryClient는 DI(종속성 주입) 컨테이너에 삽입되지 않습니다. 다음 코드에 나와 있는 것처럼 TelemetryClient의 새 인스턴스를 만들고 로거 공급자에서 사용하는 것과 동일한 구성을 사용해야 합니다. 이러한 요구 사항은 모든 사용자 지정 원격 분석 및 ILogger의 원격 분석에 동일한 구성이 사용되도록 합니다.

public class MyController : ApiController
{
   // This TelemetryClient instance can be used to track additional telemetry through the TrackXXX() API.
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }  
}

참고 항목

Microsoft.ApplicationInsights.AspNetCore 패키지를 사용하여 Application Insights를 사용하도록 설정하는 경우 생성자에서 직접 TelemetryClient를 가져오도록 이 코드를 수정합니다.

SDK가 설치되어 있지 않고, Azure Web Apps 확장을 사용하여 ASP.NET Core 애플리케이션에 Application Insights를 사용하도록 설정하고 있습니다. 새 공급자는 어떻게 사용하나요?

Azure Web Apps의 Application Insights 확장은 새 공급자를 사용합니다. 사용 중인 애플리케이션에 대한 appsettings.json 파일의 필터링 규칙을 수정할 수 있습니다.

다음 단계