W tym artykule wyjaśniono, kiedy i jak używać obiektów docelowych package0 dla zdarzeń rozszerzonych w programie SQL Server. Dla każdego celu niniejszy artykuł wyjaśnia:
Jego zdolności w zakresie gromadzenia i raportowania danych wysyłanych przez zdarzenia.
Jego parametry, z wyjątkiem przypadków, gdy parametr nie wymaga wyjaśnień.
W programie SSMS.exe dowiedz się, jak za pomocą Eksploratora obiektów kliknąć prawym przyciskiem myszy węzeł docelowy w sesji zdarzenia, aby ułatwić wyświetlanie danych wyjściowych.
Dane zdarzenia są przechwytywane jako ciąg znaków XML. Jednak w tym artykule dane są wyświetlane w wierszach relacyjnych. Program SSMS został użyty do wyświetlenia danych, a następnie skopiowany i wklejony do tego artykułu.
Alternatywna technika T-SQL do generowania zestawów wierszy z XML została wyjaśniona w sekcji ring_buffer. Obejmuje XQuery.
Parametry, akcje i pola
W języku Transact-SQL instrukcja CREATE EVENT SESSION ma kluczowe znaczenie dla zdarzeń rozszerzonych. Aby napisać oświadczenie, często potrzebujesz listy i opisu:
Pola powiązane z wybranym wydarzeniem.
Parametry powiązane z wybranym celem.
Instrukcje SELECT, które zwracają takie listy z widoków systemowych, są dostępne do skopiowania z następującego artykułu w sekcji C:
Parametry, pola i akcje używane w kontekście rzeczywistej instrukcji CREATE EVENT SESSION można zobaczyć pod tym linkiem.
etw_classic_sync_target cel
Zdarzenia programu SQL Server Extended mogą współpracować ze śledzeniem zdarzeń systemu Windows (ETW) w celu monitorowania aktywności systemu. Aby uzyskać więcej informacji, zobacz:
Ten obiekt docelowy ETW przetwarza synchronicznie dane, które otrzymuje, podczas gdy większość obiektów docelowych przetwarza asynchronicznie.
event_counter cel
Obiekt docelowy event_counter zlicza jedynie, ile razy wystąpi każde określone zdarzenie.
W przeciwieństwie do większości innych celów:
event_counter nie ma żadnych parametrów.
W przeciwieństwie do większości obiektów docelowych, event_counter obiekt docelowy przetwarza synchronicznie otrzymane dane.
Synchroniczny jest akceptowalny dla prostych event_counter, ponieważ event_counter wymaga tak mało przetwarzania.
Aparat bazy danych odłączy się od każdego obiektu docelowego, który jest zbyt wolny, co grozi spowolnieniem wydajności aparatu bazy danych. Jest to jeden z powodów, dla których większość celów przetwarza się asynchronicznie.
Przykładowe dane wyjściowe przechwycone przez event_counter
Dalej jest SESJA TWORZENIA ZDARZENIA, która doprowadziła do poprzednich wyników. W tym teście, na WYDARZENIU... WHERE, pole package0.counter zostało użyte do przerwania liczenia po wzroście liczenia do 4.
.SQL
CREATEEVENTSESSION [event_counter_1]
ONSERVERADDEVENT sqlserver.checkpoint_begin -- Test by issuing CHECKPOINT; statements.
(
WHERE ([package0].[counter] <= (4)) -- A predicate filter.
)
ADD TARGET package0.event_counter
WITH
(
MAX_MEMORY = 4096 KB,
MAX_DISPATCH_LATENCY = 3SECONDS
);
event_file cel
Obiekt docelowy event_file zapisuje dane wyjściowe sesji zdarzenia z bufora do pliku na dysku:
Parametr filename= określa się w klauzuli ADD TARGET.
.xel musi być rozszerzeniem pliku.
Wybrana nazwa pliku jest używana przez system jako prefiks, do którego dołączana jest długa liczba całkowita oparta na dacie i godzinie, po której następuje rozszerzenie xel.
UTWÓRZ SESJĘ ZDARZENIA z event_file obiektem docelowym
Dalej jest CREATE EVENT SESSION, z którą testowaliśmy. Jedna z klauzul ADD TARGET określa event_file.
.SQL
CREATEEVENTSESSION [locks_acq_rel_eventfile_22]
ONSERVERADDEVENT sqlserver.lock_acquired
(
SET
collect_database_name=(1),
collect_resource_description=(1)
ACTION (sqlserver.sql_text,sqlserver.transaction_id)
WHERE
(
[database_name]=N'InMemTest2'AND
[object_id]=(370100359)
)
),
ADDEVENT sqlserver.lock_released
(
SET
collect_database_name=(1),
collect_resource_description=(1)
ACTION(sqlserver.sql_text,sqlserver.transaction_id)
WHERE
(
[database_name]=N'InMemTest2'AND
[object_id]=(370100359)
)
)
ADD TARGET package0.event_counter,
ADD TARGET package0.event_file
(
SET filename=N'C:\Junk\locks_acq_rel_eventfile_22-.xel'
)
WITH
(
MAX_MEMORY=4096 KB,
MAX_DISPATCH_LATENCY=10SECONDS
);
sys.fn_xe_file_target_read_file funkcja;
Obiekt docelowy event_file przechowuje otrzymane dane w formacie binarnym, który nie jest czytelny dla człowieka. Język Transact-SQL może raportować zawartość pliku xel przez polecenie SELECTing z funkcji sys.fn_xe_file_target_read_file.
W przypadku programu SQL Server 2016 i nowszych wersji następujące T-SQL SELECT zgłosiło dane. Sufiks *.xel w nazwie pliku jest wymagany.
.SQL
SELECT f.*
--,CAST(f.event_data AS XML) AS [Event-Data-Cast-To-XML] -- OptionalFROM
sys.fn_xe_file_target_read_file(
'C:\junk\locks_acq_rel_eventfile_22-*.xel',
null, null, null) AS f;
W przypadku programu SQL Server 2014 SELECT podobny do poniższego raportuje dane. Po programie SQL Server 2014 pliki xem nie są już używane.
.SQL
SELECT f.*
--,CAST(f.event_data AS XML) AS [Event-Data-Cast-To-XML] -- OptionalFROM
sys.fn_xe_file_target_read_file(
'C:\junk\locks_acq_rel_eventfile_22-*.xel',
'C:\junk\metafile.xem',
null, null) AS f;
Oczywiście można również ręcznie użyć interfejsu użytkownika programu SSMS, aby wyświetlić dane xel.
Dane przechowywane w event_file celu
Dalej jest raport z SELECTing from , w SQL Server 2016.sys.fn_xe_file_target_read_file
Cel histogramu jest bardziej wyszukany niż cel event_counter. Histogram może wykonywać następujące czynności:
Policz wystąpienia dla kilku elementów osobno.
Zliczanie wystąpień różnych typów elementów:
Pola zdarzeń.
Akcje.
Parametr source_type jest kluczem do kontrolowania docelowego histogramu:
source_type=0 - Oznacza zbieranie danych dla pól zdarzeń).
source_type=1 - Oznacza zbieranie danych dla akcji.
Wartość domyślna to 1.
Domyślny parametr "slots" to 256. Jeśli przypiszesz inną wartość, wartość zostanie zaokrąglona w górę do następnej potęgi 2.
Na przykład slots=59 zostanie zaokrąglone w górę do =64.
Podczas sesji zdarzeń rozszerzonych z histogramem jako celem czasami można zobaczyć nieoczekiwane wyniki. Niektóre zdarzenia mogą nie być wyświetlane w tym samym czasie, gdy liczba innych zdarzeń ma wyższą wartość niż powinna.
Jest to efekt uboczny projektu docelowego histogramu. Jednostka histogramu używa funkcji mieszania do agregowania jednostek w segmentach. W związku z tym, w zależności od wyboru pola agregacji, dwa obiekty mogą być przechowywane w tym samym zasobniku i oba obiekty są wyświetlane pod nazwą tego wykonanego jako pierwszy.
Może się to również zdarzyć, gdy używasz parametru. Rozważmy następujący scenariusz:NO_EVENT_LOSS
Skonfigurowano sesję zdarzeń rozszerzonych, używając histogramu jako elementu docelowego i grupując według , aby zebrać wykonanie procedury przechowywanej.object_id
Procedura składowana jest wykonywana A. Następnie należy wykonać procedurę składowaną B.
Jeśli obie procedury składowane zwrócą tę samą wartość dla funkcji skrótu, histogram pokaże dwukrotne wykonanie procedury składowanej A, a procedura składowana B nie zostanie wyświetlona.object_id
Przykład działania dla histogramu
Na swoim TARGET... Klauzula SET, poniższa instrukcja Transact-SQL CREATE EVENT SESSION określa przypisanie parametru docelowego source_type=1. 1 oznacza, że cel histogramu śledzi akcję.
W tym przykładzie ZDARZENIE... Oferta klauzuli ACTION oferuje tylko jedno działanie do wyboru przez cel, a mianowicie . Na TARGET... SET, widzimy przypisanie przypisania.sqlos.system_thread_idsource=N'sqlos.system_thread_id'
Uwaga
Nie można dodać więcej niż jednego obiektu docelowego tego samego typu (w tym celu histogramu) na sesję zdarzenia. Nie jest również możliwe posiadanie więcej niż jednego źródła (pola akcji/zdarzenia) na cel histogramu. W związku z tym nowa sesja zdarzenia jest wymagana do śledzenia wszelkich dodatkowych pól akcji (lub zdarzenia) w nowym celu histogramu.
The following data was captured. The values under the value column were system_thread_id values. For instance, a total of 236 locks were taken under thread 6540.
The C.3 SELECT statement can find the actions that the system has available for you to specify on your CREATE EVENT SESSION statement. In the WHERE clause, you would first edit the filter to match the actions that interest you.o.name LIKE
Next is a sample rowset returned by the C.3 SELECT. The action is seen in the second row.system_thread_id
Package-Name Action-Name Action-Description
------------ ----------- ------------------
package0 collect_current_thread_id Collect the current Windows thread ID
sqlos system_thread_id Collect current system thread ID
sqlserver create_dump_all_threads Create mini dump including all threads
sqlserver create_dump_single_thread Create mini dump for the current thread
Event field example for histogram
The following example sets source_type=0. The value assigned to source= is an event field (not an action).
The following data was captured by the histogram target. The data shows that the database that is ID=5 experienced 7 checkpoint_begin events.
value count
----- -----
5 7
7 4
6 3
SELECT to discover available fields on your chosen event
The C.4 SELECT statement shows event fields that you can choose from. You would first edit the filter to be your chosen event name.o.name LIKE
The following rowset was returned by the C.4 SELECT. The rowset shows that is the only field on the event that can supply values for the histogram target.database_idcheckpoint_begin
The pair_matching target enables you to detect start events that occur without a corresponding end event. For instance, it might be a problem when a event occurs but no matching event follows in a timely manner.lock_acquiredlock_released
The system doesn't automatically match start and end events. Instead, you explain the matching to the system in your CREATE EVENT SESSION statement. When a start and end event are matched, the pair is discarded so everyone can focus on the unmatched start events.
Finding matchable fields for the start and end event pair
By using the C.4 SELECT, we see in the following rowset there are about 16 fields for the event. The rowset displayed here has been manually split to show which fields our example matched on. Some fields would be silly to try matching, such as on the of both events.lock_acquiredduration
Package-Name Event-Name Field-Name Field-Description
------------ ---------- ---------- -----------------
sqlserver lock_acquired database_name NULL
sqlserver lock_acquired mode NULL
sqlserver lock_acquired resource_0 The ID of the locked object, when lock_resource_type is OBJECT.
sqlserver lock_acquired resource_1 NULL
sqlserver lock_acquired resource_2 The ID of the lock partition, when lock_resource_type is OBJECT, and resource_1 is 0.
sqlserver lock_acquired transaction_id NULL
sqlserver lock_acquired associated_object_id The ID of the object that requested the lock that was acquired.
sqlserver lock_acquired database_id NULL
sqlserver lock_acquired duration The time (in microseconds) between when the lock was requested and when it was canceled.
sqlserver lock_acquired lockspace_nest_id NULL
sqlserver lock_acquired lockspace_sub_id NULL
sqlserver lock_acquired lockspace_workspace_id NULL
sqlserver lock_acquired object_id The ID of the locked object, when lock_resource_type is OBJECT. For other lock resource types it will be 0
sqlserver lock_acquired owner_type NULL
sqlserver lock_acquired resource_description The description of the lock resource. The description depends on the type of lock. This is the same value as the resource_description column in the sys.dm_tran_locks view.
sqlserver lock_acquired resource_type NULL
Example of pair_matching
The following CREATE EVENT SESSION statement specifies two events, and two targets. The pair_matching target specifies two sets of fields to match the events into pairs. The sequence of comma-delimited fields assigned to and must be the same. No tabs or newlines are allowed between the fields mentioned in the comma-delimited value, although spaces are okay.begin_matching_columns=end_matching_columns=
To narrow the results, we first selected from to find the of our test table. We added a filter for that one ID to the EVENT...WHERE clause.sys.objectsobject_id
To test the event session, we purposely prevented to acquired locks from being released. We did this with the following T-SQL steps:
BEGIN TRANSACTION.
UPDATE MyTable....
Purposely not issue a COMMIT TRANSACTION, until after we examined the targets.
Later after testing, we issued a COMMIT TRANSACTION.
The simple event_counter target provided the following output rows. Because 52-50=2, the output implies we will see 2 unpaired lock_acquired events when we examine the output from the pair-matching target.
The pair_matching target provided the following output. As suggested by the event_counter output, we do indeed see two lock_acquired rows. The fact that we see these rows at all means these two lock_acquired events are unpaired.
The rows for the unpaired lock_acquired events could include the T-SQL text, or , that took the locks. But we didn't want to bloat the display.sqlserver.sql_text
ring_buffer target
The ring_buffer target is handy for quick and simple event testing. When you stop the event session, the stored output is discarded.
In this ring_buffer section, we also show how you can use the Transact-SQL implementation of XQuery to copy the XML contents of the ring_buffer into a more readable relational rowset.
CREATE EVENT SESSION with ring_buffer
There is nothing special about this CREATE EVENT SESSION statement, which uses the ring_buffer target.
SQL
CREATEEVENTSESSION [ring_buffer_lock_acquired_4]
ONSERVERADDEVENT sqlserver.lock_acquired
(
SET collect_resource_description=(1)
ACTION(sqlserver.database_name)
WHERE
(
[object_id]=(370100359) -- ID of MyTableAND
sqlserver.database_name='InMemTest2'
)
)
ADD TARGET package0.ring_buffer
(
SET max_events_limit=(98)
)
WITH
(
MAX_MEMORY=4096 KB,
MAX_DISPATCH_LATENCY=3SECONDS
);
XML output received for lock_acquired by ring_buffer
When retrieved by a SELECT statement, the content is in the form of a string of XML. The XML string that was stored by the ring_buffer target in our testing, is shown next. However, for brevity of the following XML display, all but two elements have been erased. Further, within each , a handful of extraneous elements have been deleted.<event><event><data>
To see the preceding XML, you can issue the following SELECT while the event session is active. The active XML data is retrieved from the system view .sys.dm_xe_session_targets
SQL
SELECTCAST(LocksAcquired.TargetXml ASXML) AS RBufXml
INTO
#XmlAsTable
FROM
(
SELECTCAST(t.target_data ASXML) AS TargetXml
FROM
sys.dm_xe_session_targets AS t
JOIN sys.dm_xe_sessions AS s
ON s.address = t.event_session_address
WHERE
t.target_name = 'ring_buffer'AND
s.name = 'ring_buffer_lock_acquired_4'
)
AS LocksAcquired;
SELECT * FROM #XmlAsTable;
XQuery to see the XML as a rowset
To see the preceding XML as a relational rowset, continue from the preceding SELECT statement by issuing the following T-SQL. The commented lines explain each use of XQuery.
SQL
SELECT-- (A)
ObjectLocks.value('(@timestamp)[1]',
'datetime' ) AS [OccurredDtTm]
-- (B)
,ObjectLocks.value('(data[@name="mode"]/text)[1]',
'nvarchar(32)' ) AS [Mode]
-- (C)
,ObjectLocks.value('(data[@name="transaction_id"]/value)[1]',
'bigint' ) AS [TxnId]
-- (D)
,ObjectLocks.value('(action[@name="database_name" and @package="sqlserver"]/value)[1]',
'nvarchar(128)') AS [DatabaseName]
FROM
#TableXmlCell
CROSSAPPLY-- (E)
TargetDateAsXml.nodes('/RingBufferTarget/event[@name="lock_acquired"]') AS T(ObjectLocks);
XQuery notes from preceding SELECT
(A)
timestamp= attribute's value, on <event> element.
The '(...)[1]' construct ensures only one value returned per iteration, as is a required limitation of the .value() XQuery method of XML data type variable and columns.
(B)
<text> element's inner value, within a <data> element which has its name= attribute equal to "mode".
(C)
<value> elements inner value, within a <data> element which has its name= attribute equal to "transaction_id".
(D)
<event> contains <action>.
<action> having name= attribute equal to "database_name", and package= attribute equal to "sqlserver" (not "package0"), get the inner value of <value> element.
(E)
C.A. causes processing to repeat for every individual <event> element which has its name= attribute equal to "lock_acquired".
This applies to the XML returned by the preceding FROM clause.
Output from XQuery SELECT
Next is the rowset generated by the preceding T-SQL, which includes XQuery.
Package0 has two more targets, but they cannot be used in Transact-SQL:
compressed_history
event_stream
One way we know those two targets can't be used in T-SQL is that their non-null values in the column sys.dm_xe_objects.capabilities don't include the bit 0x1.
The event_stream target can be used in .NET programs written in languages like C#. C# and other .NET developers can access an event stream through a .NET Framework class, such as in namespace .Microsoft.SqlServer.XEvents.Linq
If encountered, error 25726 means the event stream filled up with data faster than the client could consume the data. This causes the database engine to disconnect from the event stream to avoid slowing the performance of the server.