.NET용 X-Ray SDK로 SQL 쿼리 추적하기
.NET용 X-Ray SDK는 SqlCommand
대신 사용할 수 있는 System.Data.SqlClient.SqlCommand
용 래퍼 클래스 TraceableSqlCommand
를 제공합니다. TraceableSqlCommand
클래스를 사용하여 SQL 명령을 초기화할 수 있습니다.
동기 및 비동기 메서드를 사용하여 SQL 쿼리 추적
다음 예제에서는 TraceableSqlCommand
를 사용하여 동기식 및 비동기식으로 SQL Server 쿼리를 자동으로 추적하는 방법을 보여 줍니다.
예 Controller.cs
- SQL 클라이언트 구성(동기)
using Amazon;
using Amazon.Util;
using Amazon.XRay.Recorder.Core;
using Amazon.XRay.Recorder.Handlers.SqlServer;
private void QuerySql(int id)
{
var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"];
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new TraceableSqlCommand("SELECT " + id, sqlConnection))
{
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
ExecuteReaderAsync
메서드를 사용하여 비동기식으로 쿼리를 실행할 수 있습니다.
예 Controller.cs
- SQL 클라이언트 구성(비동기)
using Amazon;
using Amazon.Util;
using Amazon.XRay.Recorder.Core;
using Amazon.XRay.Recorder.Handlers.SqlServer;
private void QuerySql(int id)
{
var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"];
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new TraceableSqlCommand("SELECT " + id, sqlConnection))
{
await sqlCommand.ExecuteReaderAsync();
}
}
SQL Server에 수행된 SQL 쿼리 수집
SqlCommand.CommandText
캡처를 SQL 쿼리에서 생성된 하위 세그먼트의 일부로 사용할 수 있습니다. SqlCommand.CommandText
는 하위 세그먼트 JSON에서 sanitized_query
필드로 나타납니다. 보안을 위해 이 기능은 기본적으로 비활성화 상태입니다.
참고
중요한 정보를 일반 텍스트로 SQL 쿼리에 포함시키는 경우 수집 기능을 활성화하지 마십시오.
다음 두 가지 방법으로 SQL 쿼리 수집을 활성화할 수 있습니다.
-
애플리케이션에 대한 글로벌 구성에서
CollectSqlQueries
속성을true
로 설정합니다. -
TraceableSqlCommand
인스턴스를collectSqlQueries
파라미터를true
로 설정하여 인스턴스 내의 호출을 수집합니다.
글로벌 CollectSqlQueries 속성 활성화
다음 예제에서는 .NET 및 .NET Core에 대해 CollectSqlQueries
속성을 활성화하는 방법을 보여 줍니다.
collectSqlQueries 파라미터 활성화
TraceableSqlCommand
인스턴스의 collectSqlQueries
파라미터를 true
로 설정하여 해당 인스턴스에서 수행된 SQL Server 쿼리에 대한 SQL 쿼리 텍스트를 수집할 수 있습니다. 파라미터를 false
로 설정하면 TraceableSqlCommand
인스턴스에 대한 CollectSqlQuery
기능이 비활성화됩니다.
참고
TraceableSqlCommand
인스턴스의 collectSqlQueries
값은 CollectSqlQueries
속성의 글로벌 구성에서 설정된 값을 재정의합니다.
예제 Controller.cs
– 인스턴스에 대한 SQL 쿼리 수집 활성화
using Amazon;
using Amazon.Util;
using Amazon.XRay.Recorder.Core;
using Amazon.XRay.Recorder.Handlers.SqlServer;
private void QuerySql(int id)
{
var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"];
using (var sqlConnection = new SqlConnection(connectionString))
using (var command = new TraceableSqlCommand("SELECT " + id, sqlConnection, collectSqlQueries: true))
{
command.ExecuteNonQuery();
}
}