![]() |
VOOZH | about |
dotnet add package Azure.Monitor.Query.Logs --version 1.0.0
NuGet\Install-Package Azure.Monitor.Query.Logs -Version 1.0.0
<PackageReference Include="Azure.Monitor.Query.Logs" Version="1.0.0" />
<PackageVersion Include="Azure.Monitor.Query.Logs" Version="1.0.0" />Directory.Packages.props
<PackageReference Include="Azure.Monitor.Query.Logs" />Project file
paket add Azure.Monitor.Query.Logs --version 1.0.0
#r "nuget: Azure.Monitor.Query.Logs, 1.0.0"
#:package Azure.Monitor.Query.Logs@1.0.0
#addin nuget:?package=Azure.Monitor.Query.Logs&version=1.0.0Install as a Cake Addin
#tool nuget:?package=Azure.Monitor.Query.Logs&version=1.0.0Install as a Cake Tool
The Azure Monitor Query Logs client library is used to execute read-only queries against Azure Monitor Logs.
Source code | Package (NuGet) | API reference documentation | Product documentation | Samples
Install the Azure Monitor Query Logs client library for .NET with NuGet:
dotnet add package Azure.Monitor.Query.Logs
An authenticated LogsQueryClient is required to query logs. To authenticate, you'll pass an instance of a TokenCredential to the constructor when creating your client. For example, the following illustration uses DefaultAzureCredential for authentication.
var client = new LogsQueryClient(new DefaultAzureCredential());
By default, the client is configured to use the Azure Public Cloud. To use a sovereign cloud instead, set the Audience property on the appropriate Options-suffixed class. For example:
// LogsQueryClient - by default, Azure Public Cloud is used
var logsQueryClient = new LogsQueryClient(
new DefaultAzureCredential());
// LogsQueryClient With Audience Set
var logsQueryClientOptions = new LogsQueryClientOptions
{
Audience = LogsQueryAudience.AzureChina
};
var logsQueryClientChina = new LogsQueryClient(
new DefaultAzureCredential(),
logsQueryClientOptions);
For examples of Logs and Metrics queries, see the Examples section.
The Log Analytics service applies throttling when the request rate is too high. Limits, such as the maximum number of rows returned, are also applied on the Kusto queries. For more information, see Query API.
All client instance methods are thread-safe and independent of each other (guideline). This design ensures that the recommendation of reusing client instances is always safe, even across threads.
Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime
You can query logs by Log Analytics workspace ID or Azure resource ID. The result is returned as a table with a collection of rows.
To query by workspace ID, use the LogsQueryClient.QueryWorkspaceAsync method:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
Response<LogsQueryResult> result = await client.QueryWorkspaceAsync(
workspaceId,
"AzureActivity | top 10 by TimeGenerated",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
LogsTable table = result.Value.Table;
foreach (var row in table.Rows)
{
Console.WriteLine($"{row["OperationName"]} {row["ResourceGroup"]}");
}
To query by resource ID, use the LogsQueryClient.QueryResourceAsync method.
To find the resource ID:
id property.var client = new LogsQueryClient(new DefaultAzureCredential());
string resourceId = "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource>";
string tableName = "<table_name>";
Response<LogsQueryResult> results = await client.QueryResourceAsync(
new ResourceIdentifier(resourceId),
$"{tableName} | distinct * | project TimeGenerated",
new LogsQueryTimeRange(TimeSpan.FromDays(7)));
LogsTable resultTable = results.Value.Table;
foreach (LogsTableRow row in resultTable.Rows)
{
Console.WriteLine($"{row["OperationName"]} {row["ResourceGroup"]}");
}
foreach (LogsTableColumn columns in resultTable.Columns)
{
Console.WriteLine("Name: " + columns.Name + " Type: " + columns.Type);
}
The QueryWorkspace method returns the LogsQueryResult, while the QueryBatch method returns the LogsBatchQueryResult. Here's a hierarchy of the response:
LogsQueryResult
|---Error
|---Status
|---Table
|---Name
|---Columns (list of `LogsTableColumn` objects)
|---Name
|---Type
|---Rows (list of `LogsTableRows` objects)
|---Count
|---AllTables (list of `LogsTable` objects)
You can map logs query results to a model using the LogsQueryClient.QueryWorkspaceAsync<T> method:
public class MyLogEntryModel
{
public string ResourceGroup { get; set; }
public int Count { get; set; }
}
var client = new LogsQueryClient(new DefaultAzureCredential());
string workspaceId = "<workspace_id>";
// Query TOP 10 resource groups by event count
Response<IReadOnlyList<MyLogEntryModel>> response = await client.QueryWorkspaceAsync<MyLogEntryModel>(
workspaceId,
"AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
foreach (var logEntryModel in response.Value)
{
Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
}
If your query returns a single column (or a single value) of a primitive type, use the LogsQueryClient.QueryWorkspaceAsync<T> overload to deserialize it:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
// Query TOP 10 resource groups by event count
Response<IReadOnlyList<string>> response = await client.QueryWorkspaceAsync<string>(
workspaceId,
"AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count | project ResourceGroup",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
foreach (var resourceGroup in response.Value)
{
Console.WriteLine(resourceGroup);
}
You can also dynamically inspect the list of columns. The following example prints the query result as a table:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
Response<LogsQueryResult> response = await client.QueryWorkspaceAsync(
workspaceId,
"AzureActivity | top 10 by TimeGenerated",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
LogsTable table = response.Value.Table;
foreach (var column in table.Columns)
{
Console.Write(column.Name + ";");
}
Console.WriteLine();
var columnCount = table.Columns.Count;
foreach (var row in table.Rows)
{
for (int i = 0; i < columnCount; i++)
{
Console.Write(row[i] + ";");
}
Console.WriteLine();
}
You can execute multiple logs queries in a single request using the LogsQueryClient.QueryBatchAsync method:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
// Query TOP 10 resource groups by event count
// And total event count
var batch = new LogsBatchQuery();
string countQueryId = batch.AddWorkspaceQuery(
workspaceId,
"AzureActivity | count",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
string topQueryId = batch.AddWorkspaceQuery(
workspaceId,
"AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
new LogsQueryTimeRange(TimeSpan.FromDays(1)));
Response<LogsBatchQueryResultCollection> response = await client.QueryBatchAsync(batch);
var count = response.Value.GetResult<int>(countQueryId).Single();
var topEntries = response.Value.GetResult<MyLogEntryModel>(topQueryId);
Console.WriteLine($"AzureActivity has total {count} events");
foreach (var logEntryModel in topEntries)
{
Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
}
Some logs queries take longer than 3 minutes to execute. The default server timeout is 3 minutes. You can increase the server timeout to a maximum of 10 minutes. In the following example, the LogsQueryOptions object's ServerTimeout property is used to set the server timeout to 10 minutes:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
// Query TOP 10 resource groups by event count
Response<IReadOnlyList<string>> response = await client.QueryWorkspaceAsync<string>(
workspaceId,
@"AzureActivity
| summarize Count = count() by ResourceGroup
| top 10 by Count
| project ResourceGroup",
new LogsQueryTimeRange(TimeSpan.FromDays(1)),
new LogsQueryOptions
{
ServerTimeout = TimeSpan.FromMinutes(10)
});
foreach (var resourceGroup in response.Value)
{
Console.WriteLine(resourceGroup);
}
To run the same logs query against multiple workspaces, use the LogsQueryOptions.AdditionalWorkspaces property:
string workspaceId = "<workspace_id>";
string additionalWorkspaceId = "<additional_workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
// Query TOP 10 resource groups by event count
Response<IReadOnlyList<string>> response = await client.QueryWorkspaceAsync<string>(
workspaceId,
@"AzureActivity
| summarize Count = count() by ResourceGroup
| top 10 by Count
| project ResourceGroup",
new LogsQueryTimeRange(TimeSpan.FromDays(1)),
new LogsQueryOptions
{
AdditionalWorkspaces = { additionalWorkspaceId }
});
foreach (var resourceGroup in response.Value)
{
Console.WriteLine(resourceGroup);
}
To get logs query execution statistics, such as CPU and memory consumption:
LogsQueryOptions.IncludeStatistics property to true.GetStatistics method on the LogsQueryResult object.The following example prints the query execution time:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
Response<LogsQueryResult> response = await client.QueryWorkspaceAsync(
workspaceId,
"AzureActivity | top 10 by TimeGenerated",
new LogsQueryTimeRange(TimeSpan.FromDays(1)),
new LogsQueryOptions
{
IncludeStatistics = true,
});
BinaryData stats = response.Value.GetStatistics();
using var statsDoc = JsonDocument.Parse(stats);
var queryStats = statsDoc.RootElement.GetProperty("query");
Console.WriteLine(queryStats.GetProperty("executionTime").GetDouble());
Because the structure of the statistics payload varies by query, a BinaryData return type is used. It contains the raw JSON response. The statistics are found within the query property of the JSON. For example:
{
"query": {
"executionTime": 0.0156478,
"resourceUsage": {...},
"inputDatasetStatistics": {...},
"datasetStatistics": [{...}]
}
}
To get visualization data for logs queries using the render operator:
LogsQueryOptions.IncludeVisualization property to true.GetVisualization method on the LogsQueryResult object.For example:
string workspaceId = "<workspace_id>";
var client = new LogsQueryClient(new DefaultAzureCredential());
Response<LogsQueryResult> response = await client.QueryWorkspaceAsync(
workspaceId,
@"StormEvents
| summarize event_count = count() by State
| where event_count > 10
| project State, event_count
| render columnchart",
new LogsQueryTimeRange(TimeSpan.FromDays(1)),
new LogsQueryOptions
{
IncludeVisualization = true,
});
BinaryData viz = response.Value.GetVisualization();
using var vizDoc = JsonDocument.Parse(viz);
var queryViz = vizDoc.RootElement.GetProperty("visualization");
Console.WriteLine(queryViz.GetString());
Because the structure of the visualization payload varies by query, a BinaryData return type is used. It contains the raw JSON response. For example:
{
"visualization": "columnchart",
"title": null,
"accumulate": false,
"isQuerySorted": false,
"kind": null,
"legend": null,
"series": null,
"yMin": "",
"yMax": "",
"xAxis": null,
"xColumn": null,
"xTitle": null,
"yAxis": null,
"yColumns": null,
"ySplit": null,
"yTitle": null,
"anomalyColumns": null
}
To register a client with the dependency injection container, invoke AddLogsQueryClient. For more information, see Register client.
To diagnose various failure scenarios, see the troubleshooting guide.
To learn more about Azure Monitor, see the Azure Monitor service documentation.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately with labels and comments. Follow the instructions provided by the bot. You'll only need to sign the CLA once across all Microsoft repos.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact with any questions or comments.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 netstandard2.0 is compatible. netstandard2.1 netstandard2.1 was computed. |
| .NET Framework | net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 3 NuGet packages that depend on Azure.Monitor.Query.Logs:
| Package | Downloads |
|---|---|
|
FoundationaLLM.Common
FoundationaLLM.Common is a .NET library that the FoundationaLLM.Client.Core and FoundationaLLM.Client.Management client libraries share as a common dependency. |
|
|
Quilt4Net.Toolkit
Tools for Health checks via Quilt4Net.Toolkit.Api and Application Insigts. |
|
|
Atc.LogAnalytics
Atc.LogAnalytics contains a .NET library designed to facilitate the execution of KQL queries within Azure Log Analytics environments |
Showing the top 3 popular GitHub repositories that depend on Azure.Monitor.Query.Logs:
| Repository | Stars |
|---|---|
|
microsoft/mcp
Catalog of official Microsoft MCP (Model Context Protocol) server implementations for AI-powered data access and tool integration
|
|
|
Altinn/altinn-studio
Next generation open source Altinn platform and applications.
|
|
|
NeilMacMullen/kusto-loco
C# KQL query engine with flexible I/O layers and visualization
|
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 642,631 | 10/17/2025 |