LLI Wiki — My Digital Knowledge Base

Azure SQL Database: tracing errors, deadlocks and timeouts with Extended Events to Blob (managed identity)

A database scoped XEvents session that writes every SQL error, deadlock graph and attention to a Blob container through the managed identity: create, read, clean up and pitfalls (Msg 25744).

When an application complains about "random SQL errors" or deadlocks, the first question is always the same: which ones, when, and who caused them? Azure SQL Database has no error log to open like a classic SQL Server. My answer: an Extended Events session that writes to a Blob container, authenticated with the managed identity of the logical server. No SAS token to renew, no secret to store.

The session captures three things:

Event What it captures
sqlserver.error_reported Every SQL error (severity ≥ 11): number, severity, state, message
sqlserver.database_xml_deadlock_report The full XML graph of each deadlock (the Azure SQL Database event)
sqlserver.attention Requests cancelled by the client: command timeout, cancel
flowchart LR
    A["Azure SQL database"] --> B["XEvents session (ON DATABASE)"]
    B --> C["Credential: MANAGED IDENTITY"]
    C --> D["Blob container (.xel files)"]
    D --> E["fn_xe_file_target_read_file"]
    D --> F["SSMS: Merge Extended Events files"]

1. Azure prerequisites (once)

  1. SQL logical server → Identity: a managed identity is enabled (system assigned, or the primary user assigned one).
  2. On the container → Access Control (IAM) → Storage Blob Data Contributor role for that identity.
  3. If the storage firewall is on: add the Microsoft.Sql/servers instance under Resource instances.
  4. No immutability policy, no hierarchical namespace, Hot tier.

Azure SQL Database: a database scoped credential, created in the database you trace (not in master). Managed Instance and SQL Server: a server scoped credential (CREATE CREDENTIAL) and ON SERVER sessions.

2. Create

IF NOT EXISTS (SELECT 1 FROM sys.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##')
    CREATE MASTER KEY;

-- Credential name = the container URL, WITHOUT a trailing "/"
CREATE DATABASE SCOPED CREDENTIAL
    [https://stdbacontoso.blob.core.windows.net/xevents]
WITH IDENTITY = 'MANAGED IDENTITY';

CREATE EVENT SESSION [xe_errors]
ON DATABASE
ADD EVENT sqlserver.error_reported
(
    ACTION
    (
        sqlserver.database_name, sqlserver.username,
        sqlserver.client_hostname, sqlserver.client_app_name,
        sqlserver.session_id, sqlserver.sql_text
    )
    WHERE severity >= 11            -- below: informational messages
),
ADD EVENT sqlserver.database_xml_deadlock_report
(
    ACTION (sqlserver.database_name)
),
ADD EVENT sqlserver.attention
(
    ACTION
    (
        sqlserver.database_name, sqlserver.username,
        sqlserver.client_hostname, sqlserver.client_app_name,
        sqlserver.session_id, sqlserver.sql_text
    )
)
ADD TARGET package0.event_file
(
    SET filename = N'https://stdbacontoso.blob.core.windows.net/xevents/xe_errors.xel',
        max_file_size = 100,        -- MB per file
        max_rollover_files = 10
)
WITH
(
    STARTUP_STATE = ON,             -- restarts after a failover; OFF for an ad hoc trace
    EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
    MAX_DISPATCH_LATENCY = 30 SECONDS
);

ALTER EVENT SESSION [xe_errors] ON DATABASE STATE = START;

To check:

SELECT name, credential_identity, create_date FROM sys.database_scoped_credentials;

SELECT s.name, t.target_name, s.total_buffer_size + s.total_target_memory AS session_memory
FROM sys.dm_xe_database_sessions AS s
JOIN sys.dm_xe_database_session_targets AS t ON s.address = t.event_session_address;

3. Read the events

On Azure, fn_xe_file_target_read_file needs the exact file name: I take it from the session. For big files (1 GB and more) I skip T-SQL: I download the .xel files and open them in SSMS (File → Open → Merge Extended Events files).

DECLARE @file nvarchar(4000) =
(
    SELECT CAST(t.target_data AS xml).value('(EventFileTarget/File/@name)[1]', 'nvarchar(4000)')
    FROM sys.dm_xe_database_session_targets AS t
    JOIN sys.dm_xe_database_sessions AS s ON s.address = t.event_session_address
    WHERE s.name = N'xe_errors' AND t.target_name = N'event_file'
);

-- Errors and attentions
SELECT
    x.value('(event/@timestamp)[1]',                            'datetime2(3)')  AS ts_utc,
    x.value('(event/@name)[1]',                                 'sysname')       AS event_name,
    x.value('(event/data[@name="error_number"]/value)[1]',      'int')           AS error_number,
    x.value('(event/data[@name="severity"]/value)[1]',          'int')           AS severity,
    x.value('(event/data[@name="message"]/value)[1]',           'nvarchar(max)') AS message,
    x.value('(event/action[@name="username"]/value)[1]',        'sysname')       AS username,
    x.value('(event/action[@name="client_hostname"]/value)[1]', 'nvarchar(256)') AS client_host,
    x.value('(event/action[@name="client_app_name"]/value)[1]', 'nvarchar(256)') AS client_app,
    x.value('(event/action[@name="sql_text"]/value)[1]',        'nvarchar(max)') AS sql_text
FROM (SELECT CAST(event_data AS xml) AS x
      FROM sys.fn_xe_file_target_read_file(@file, NULL, NULL, NULL)
      WHERE object_name IN (N'error_reported', N'attention')) AS e
ORDER BY ts_utc DESC;

-- Deadlocks: save the XML as .xdl to see the graph in SSMS
SELECT
    x.value('(event/@timestamp)[1]', 'datetime2(3)')               AS ts_utc,
    x.query('(event/data[@name="xml_report"]/value/deadlock)[1]') AS deadlock_xml
FROM (SELECT CAST(event_data AS xml) AS x
      FROM sys.fn_xe_file_target_read_file(@file, NULL, NULL, NULL)
      WHERE object_name = N'database_xml_deadlock_report') AS d
ORDER BY ts_utc DESC;

4. Clean up

ALTER EVENT SESSION [xe_errors] ON DATABASE STATE = STOP;
DROP EVENT SESSION [xe_errors] ON DATABASE;

-- The credential only when no other session writes to this container
SELECT name FROM sys.database_event_sessions;
DROP DATABASE SCOPED CREDENTIAL [https://stdbacontoso.blob.core.windows.net/xevents];

-- The master key only if it was created for this and no credential is left
-- DROP MASTER KEY;

On the Azure side, optionally: remove the RBAC role and delete the .xel files.

Pitfalls

Symptom Cause
Msg 25744 The action '...' is not available for Azure SQL Database Not every SQL Server action exists in Azure SQL Database: server_instance_name and server_principal_name are refused. username is enough for the identity
OS error 5 Access is denied at START Missing RBAC role, or storage firewall without an exception for the SQL server
OS error 86 network password is not correct No credential whose name matches the URL, or a trailing /
OS error 3 path not found The container does not exist
OS error 13 data is invalid An immutability policy on the container

And when the session refuses to start without a clear message: SELECT CONVERT(xml, record) FROM sys.dm_os_ring_buffers WHERE ring_buffer_type = 'RING_BUFFER_XE_LOG';

Lessons learned

See also: blocking history with Extended Events and live blocking: who, why, how.

Mastodon LLIMastodon SocialFosstodon