How to read SQL Trace(.trc) or Extended events file(.xel) for SQL server 2022 in c#.net

Deepak Rane (drane) 60 Reputation points
2023-09-20T08:52:00.1866667+00:00

Hi Team,

We need a help on parsing the data from SQL trace file(.trc) or Extended Events file (.xel) in C# application.

Required for SQL server 2017 to SQL 2022

Could you please guide us how to do that?

Regards,

Deepak Rane

SQL Server | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Dan Guzman 9,406 Reputation points
    2023-09-20T15:06:23.46+00:00

    For Extended Events, the Microsoft.SqlServer.XEvent.XELite package available on NuGet facilitates reading XE traces programmatically. The NuGet page has C# examples.

    Another method is with Microsoft.SqlServer.XEvent.Linq.QueryableXEventData. The Micrrosoft.SqlServer.XE.Core.dll and Micrrosoft.SqlServer.Xevent.Linq.dll assemblies are located in the SQL installation shared directory (e.g. C:\Program Files\Microsoft SQL Server\160\Shared). The fields and actions captured by the XE trace are exposed in separate collections. Below is a C# snippet to extract XML deadlock reports from the system_health trace:

    using (var xeEvents = new Microsoft.SqlServer.XEvent.Linq.QueryableXEventData(@"C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Log\system_health_*.xel"))
        {
            foreach (var xeEvent in xeEvents)
            {
                if (xeEvent.Name == "xml_deadlock_report")
                {
                   Console.WriteLine($"{xeEvent.Name}: {xeEvent.Fields["xml_report"].Value}");
                }
            }
    }
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,516 Reputation points
    2023-09-20T09:19:33.0166667+00:00

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.