如何读取扩展事件.xel文件

时间:2018-11-05 03:37:55

标签: sql-server

我对读取/解析扩展事件文件.xel文件有一定的要求,我该如何有效地做到这一点。我的一位同事建议使用API​​来解析文件,但是我认为应该有一种方法可以通过SQL代码本身来实现。非常感谢帮助。

2 个答案:

答案 0 :(得分:3)

要读取.xel文件,可以使用sys.fn_xe_file_target_read_file函数。例如:

select cast(event_data as XML) as event_data
from sys.fn_xe_file_target_read_file('D:\Folder\MySession*.xel', null, null, null)

此外,您可能希望解析返回的XML以获取表格式的数据。为此,您需要确定要从XML中提取哪些数据并编写适当的XPath表达式。例如:

-- You have to know element names and their data types
select
    n.value('(@name)[1]', 'varchar(50)') as event_name,
    n.value('(@package)[1]', 'varchar(50)') AS package_name,
    n.value('(@timestamp)[1]', 'datetime2') AS [utc_timestamp],
    n.value('(data[@name="duration"]/value)[1]', 'int') as duration,
    n.value('(data[@name="cpu_time"]/value)[1]', 'int') as cpu,
    n.value('(data[@name="physical_reads"]/value)[1]', 'int') as physical_reads,
    n.value('(data[@name="logical_reads"]/value)[1]', 'int') as logical_reads,
    n.value('(data[@name="writes"]/value)[1]', 'int') as writes,
    n.value('(data[@name="row_count"]/value)[1]', 'int') as row_count,
    n.value('(data[@name="last_row_count"]/value)[1]', 'int') as last_row_count,
    n.value('(data[@name="line_number"]/value)[1]', 'int') as line_number,
    n.value('(data[@name="offset"]/value)[1]', 'int') as offset,
    n.value('(data[@name="offset_end"]/value)[1]', 'int') as offset_end,
    n.value('(data[@name="statement"]/value)[1]', 'nvarchar(max)') as statement,
    n.value('(action[@name="database_name"]/value)[1]', 'nvarchar(128)') as database_name
from (select cast(event_data as XML) as event_data
from sys.fn_xe_file_target_read_file('D:\Folder\MySession*.xel', null, null, null)) ed
cross apply ed.event_data.nodes('event') as q(n)

答案 1 :(得分:2)

我从Azure SQL数据库上的审核系统获得了XEL文件,因此找到了这篇文章。但是它不能与fn_xe_file_target_read_file一起运行,因此我不得不像这样使用fn_get_audit_file

select * from sys.fn_get_audit_file('c:\temp\08_11_22_921_16*.xel', null, null)