Monitoring Logs in Azure SQL Database
Why Collect Logs?
Logs provide insight into database health, security events, and query performance. Azure SQL offers several log sources that you can query, archive, and analyze.
Available Log Types
| Log Type | Description | Retention |
|---|---|---|
| SQL Auditing | Captures database and server level activities | Up to 2 years |
| Diagnostic Settings | Writes activity, errors, and slow query logs to Log Analytics / Storage | Unlimited (depends on storage) |
| Extended Events | Fineāgrained event collection for performance troubleshooting | Custom (typically days) |
| Automatic Tuning Logs | Tracks recommended index actions and forceāapplied actions | 30 days |
Querying Logs with TāSQL
Use the builtāin views and functions to pull log data directly from the database.
-- Example: Retrieve recent audit events
SELECT
event_time,
action_id,
succeeded,
session_server_principal_name,
database_name,
statement
FROM sys.dm_audit_actions
WHERE event_time > DATEADD(hour, -24, GETUTCDATE())
ORDER BY event_time DESC;
Extended Events can be queried via the sys.dm_xe_sessions and related DMVs.
-- Example: List recent deadlock events
SELECT
DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), SYSDATETIMEOFFSET()), event_data.value('(event/@timestamp)[1]', 'datetime2')) AS EventTime,
event_data.value('(event/data/value)[1]', 'nvarchar(max)') AS DeadlockGraph
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = 'xml_deadlock_report';
Archiving Logs to Azure Storage
Configure Diagnostic Settings to send logs to a storage account, Event Hub, or Log Analytics workspace.
az monitor diagnostic-settings create \
--name sqlLogArchive \
--resource /subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.Sql/servers/{server} \
--storage-account {storageAccountId} \
--logs '[{"category":"SQLSecurityAuditEvents","enabled":true}]';
Once archived, you can use Azure Data Explorer or Power BI to visualize log trends.
Setting Up Alerts Based on Log Events
Create alert rules in Azure Monitor that trigger on specific log criteria.
az monitor metrics alert create \
--name "HighAuditFailures" \
--resource-group {rg} \
--scopes /subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.Sql/servers/{server} \
--condition "count of audit_failure where EventTime > ago(5m) >= 5" \
--action-group {actionGroupId};
Combine with Azure Functions for automated remediation.
Best Practices
- Enable Auditing and Direct to a secure storage account.
- Retain logs long enough for compliance but purge old data to control costs.
- Use Log Analytics workspaces for centralized query and visualization.
- Set up alerting on critical events such as failed logins or policy violations.
- Regularly review Extended Events for performance bottlenecks.