SqlClient에서 이벤트 추적 사용

적용 대상: .NET Framework .NET .NET Standard

ADO.NET 다운로드

ETW(Windows용 이벤트 추적)는 디버깅 및 테스트를 위해 드라이버에서 정의된 이벤트를 기록할 수 있는 효율적인 커널 수준 추적 기능입니다. SqlClient는 다양한 정보 수준에서 ETW 이벤트 캡처를 지원합니다. 이벤트 추적 캡처를 시작하려면 클라이언트 애플리케이션이 SqlClient의 EventSource 구현에서 이벤트를 수신 대기해야 합니다.

Microsoft.Data.SqlClient.EventSource

현재 구현에서는 다음과 같은 이벤트 키워드를 지원합니다.

키워드 이름 설명
ExecutionTrace 1 명령 실행 전후에 이벤트 시작/중지 캡처를 활성화합니다.
Trace 2 기본 애플리케이션 흐름 추적 이벤트 캡처를 활성화합니다.
범위 4 이벤트 입장 및 나가기 캡처를 활성화합니다
NotificationTrace 8 SqlNotification 추적 이벤트 캡처를 활성화합니다
NotificationScope 16 SqlNotification 범위 이벤트 입장 및 나가기 캡처를 활성화합니다
PoolerTrace 32 연결 풀링 흐름 추적 이벤트 캡처를 활성화합니다.
PoolerScope 64 연결 풀링 범위 추적 이벤트 캡처를 활성화합니다.
AdvancedTrace 128 고급 흐름 추적 이벤트 캡처를 활성화합니다.
AdvancedTraceBin 256 추가 정보를 사용하여 고급 흐름 추적 이벤트 캡처를 활성화합니다.
CorrelationTrace 512 상관 관계 흐름 추적 이벤트를 캡처하도록 설정합니다.
StateDump 1024 SqlConnection의 전체 상태 덤프 캡처를 활성화합니다
SNITrace 2048 Managed Networking 구현에서 흐름 추적 이벤트 캡처를 활성화합니다(.NET Core에서만 적용 가능)
SNIScope 4096 Managed Networking 구현에서 범위 이벤트 캡처를 활성화합니다(.NET Core에서만 적용 가능)

예시

다음 예에서는 AdventureWorks 샘플 데이터베이스에서 데이터 작업에 대해 이벤트 추적을 사용하도록 설정하고 콘솔 창에 이벤트를 표시합니다.

using System;
using System.Diagnostics.Tracing;
using Microsoft.Data.SqlClient;

// This listener class will listen for events from the SqlClientEventSource class.
// SqlClientEventSource is an implementation of the EventSource class which gives 
// it the ability to create events.
public class SqlClientListener : EventListener
{
    protected override void OnEventSourceCreated(EventSource eventSource)
    {
        // Only enable events from SqlClientEventSource.
        if (eventSource.Name.Equals("Microsoft.Data.SqlClient.EventSource"))
        {
            // Use EventKeyWord 2 to capture basic application flow events.
            // See the above table for all available keywords.
            EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)2);
        }
    }

    // This callback runs whenever an event is written by SqlClientEventSource.
    // Event data is accessed through the EventWrittenEventArgs parameter.
    protected override void OnEventWritten(EventWrittenEventArgs eventData)
    {
        // Print event data.
        Console.WriteLine(eventData.Payload[0]);
    }
}

class Program
{
    public static void Main()
    {
        // Create a new event listener.
        using (SqlClientListener listener = new SqlClientListener())
        {
            string connectionString = "Data Source=localhost; " +
                "Initial Catalog=AdventureWorks; Integrated Security=true";

            // Open a connection to the AdventureWorks database.
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                string sql = "SELECT * FROM Sales.Currency";
                SqlCommand command = new SqlCommand(sql, connection);

                // Perform a data operation on the server.
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    // Read the data.
                }
                reader.Close();
            }
        }
    }
}

네이티브 SNI의 이벤트 추적 지원

Microsoft.Data.SqlClient는 v2.1부터 Microsoft.Data.SqlClient.SNIMicrosoft.Data.SqlClient.SNI.runtime에서 이벤트 추적 지원을 제공합니다. XperfPerfView 도구를 사용하여 네이티브 DLL에서 이벤트를 수집할 수 있습니다.

Microsoft.Data.SqlClient v3.0부터 이벤트 수집 도구를 사용하여 클라이언트 애플리케이션을 수정하지 않고도 이벤트 추적을 사용하도록 설정할 수 있습니다.

Microsoft.Data.SqlClient v2.1에서는 이벤트 원본 수신기를 통해 EventCommand를 구성하여 이벤트 추적을 사용하도록 설정해야 합니다. 네이티브 SNI에 적용할 수 있는 유효한 EventCommand 값은 다음과 같습니다.


// Enables trace events:
EventSource.SendCommand(eventSource, (EventCommand)8192, null);

// Enables flow events:
EventSource.SendCommand(eventSource, (EventCommand)16384, null);

// Enables both trace and flow events:
EventSource.SendCommand(eventSource, (EventCommand)(8192 | 16384), null);

다음 예제에서는 네이티브 SNI DLL에서 이벤트 추적을 사용하도록 설정합니다.

// Native SNI tracing example
using System;
using System.Diagnostics.Tracing;
using Microsoft.Data.SqlClient;

public class SqlClientListener : EventListener
{
    protected override void OnEventSourceCreated(EventSource eventSource)
    {
        if (eventSource.Name.Equals("Microsoft.Data.SqlClient.EventSource"))
        {
            // Enables both trace and flow events
            EventSource.SendCommand(eventSource, (EventCommand)(8192 | 16384), null);
        }
    }
}

class Program
{
    static string connectionString = @"Data Source = localhost; Initial Catalog = AdventureWorks;Integrated Security=true;";

    static void Main(string[] args)
    {
        // Event source listener configuration is not required in v3.0 onwards.
        using (SqlClientListener listener = new SqlClientListener())
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
        }
    }
}

Xperf를 사용하여 추적 수집

  1. 다음 명령을 사용하여 추적을 시작합니다.

    xperf -start trace -f myTrace.etl -on *Microsoft.Data.SqlClient.EventSource
    
  2. 네이티브 SNI 추적 예제를 실행하여 SQL Server에 연결합니다.

  3. 다음 명령줄을 사용하여 추적을 중지합니다.

    xperf -stop trace
    
  4. PerfView를 사용하여 1단계에 지정된 myTrace.etl 파일을 엽니다. SNI 추적 로그는 Microsoft.Data.SqlClient.EventSource/SNIScopeMicrosoft.Data.SqlClient.EventSource/SNITrace 이벤트 이름으로 찾을 수 있습니다.

    PerfView를 사용하여 SNI 추적 파일 보기

PerfView를 사용하여 추적 수집

  1. PerfView를 시작하고 메뉴 모음에서 Collect > Collect을(를) 실행합니다.

  2. 추적 파일 이름, 출력 경로 및 공급자 이름을 구성합니다.

    수집하기 전에 Prefview 구성

  3. 수집을 시작합니다.

  4. 네이티브 SNI 추적 예제를 실행하여 SQL Server에 연결합니다.

  5. PerfView에서 컬렉션을 중지합니다. 2단계의 구성에 따라 PerfViewData.etl 파일을 생성하려면 시간이 소요됩니다.

  6. PerfView에서 etl 파일을 엽니다. SNI 추적 로그는 Microsoft.Data.SqlClient.EventSource/SNIScopeMicrosoft.Data.SqlClient.EventSource/SNITrace 이벤트 이름으로 찾을 수 있습니다.

dotnet-trace를 사용하여 추적 수집

Linux, macOS 또는 Windows에서 dotnet-trace를 사용하여 추적을 캡처할 수 있습니다. donet-trace 도구는 .NET 애플리케이션에 대한 추적을 수집하는 데 사용됩니다. dotnet-trace에 대한 자세한 내용은 dotnet-trace 성능 분석 유틸리티를 참조하세요. dotnet-trace에서 생성된 추적은 PerfView에서 확인할 수 있습니다.

  1. 아직 설치되지 않은 경우 클라이언트 컴퓨터에 .NET SDK를 설치합니다.

  2. dotnet-trace 설치

  3. dotnet-trace를 실행합니다. --providers 매개 변수를 사용하려면 Microsoft.Data.SqlClient의 추적에 대해 공급자 이름과 키워드를 지정해야 합니다. 키워드 옵션은 16진수로 변환된 이벤트 키워드 테이블의 키워드 값 합계입니다. 애플리케이션 시작부터 MyApplication 상세 수준의 모든 이벤트를 수집하려면 키워드의 합은 8191이며 1FFF 16진수입니다. 상세 수준은 5의 다음 명령을 통해 지정됩니다.

    dotnet-trace collect --providers Microsoft.Data.SqlClient.EventSource:1FFF:5 -- dotnet MyApplication.dll
    

    출력은 다음과 같습니다.

    
    Provider Name                           Keywords            Level               Enabled By
    Microsoft.Data.SqlClient.EventSource    0x0000000000001FFF  Verbose(5)          --providers
    
    Launching: dotnet MyApplication.dll
    Process        : /usr/lib/dotnet/dotnet
    Output File    : /home/appuser/dotnet_20240927_102506.nettrace
    
    [00:00:00:00]   Recording trace 0.00     (B)
    Press <Enter> or <Ctrl+C> to exit...
    
    Trace completed.
    Process exited with code '1'.
    

    실행 중인 애플리케이션의 정보 수준에서 모든 이벤트를 수집하려면 먼저 애플리케이션의 프로세스 ID를 찾습니다. 그런 다음 프로세스에서 dotnet-trace를 실행합니다. 정보 수준은 4에서 지정합니다.

    dotnet-trace ps
    8734  MyApplication  /home/appuser/MyApplication/MyApplication
    
    dotnet-trace collect -–process-id 8734 --providers Microsoft.Data.SqlClient.EventSource:1FFF:4
    

    애플리케이션을 별도로 실행하고 문제를 재현하는 데 필요한 한 실행되도록 합니다. CPU 사용량이 많은 문제라면 일반적인 경우 5~10초면 충분합니다.

    Provider Name                           Keywords            Level               Enabled By
    Microsoft.Data.SqlClient.EventSource    0x0000000000001FFF  LogAlways(0)        --providers
    
    Process        : /usr/lib/dotnet/dotnet
    Output File    : /home/appuser/dotnet_20240927_104154.nettrace
    
    [00:00:00:10]   Recording trace 4.096    (KB)
    Press <Enter> or <Ctrl+C> to exit...
    Stopping the trace. This may take several minutes depending on the application being traced.
    
    Trace completed.
    

    추적 파일 이름은 .nettrace(으)로 끝납니다. Windows에서 추적하지 않는 경우 파일을 Windows 시스템에 복사합니다. PerfView에서 추적 파일을 봅니다.

External resources

Microsoft.Data.SqlClient 플랫폼 간을 추적하는 방법에 대한 다른 예제 집합은 CSS SQL 네트워킹 도구 wiki를 참조하세요.

이벤트 추적에 대한 자세한 내용은 다음 리소스를 참조하세요.

리소스 설명
EventSource 클래스 ETW 이벤트를 만드는 데 사용됩니다.
EventListener 클래스 이벤트 원본에서 이벤트를 사용하도록 그리고 사용하지 않도록 설정하는 메서드를 제공합니다.