0
# Metrics and Baselines
1
2
Comprehensive metric data retrieval and analysis capabilities for Azure resources, including metric values, definitions, namespaces, and baseline comparisons for performance monitoring and trend analysis.
3
4
## Capabilities
5
6
### Metric Data Retrieval
7
8
Query metric values for Azure resources with flexible filtering, aggregation, and time range options.
9
10
```python { .api }
11
def list(resource_uri: str, timespan: Optional[str] = None, interval: Optional[str] = None, metricnames: Optional[str] = None, aggregation: Optional[str] = None, top: Optional[int] = None, orderby: Optional[str] = None, filter: Optional[str] = None, result_type: Optional[ResultType] = None, metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, rollupby: Optional[str] = None, **kwargs: Any) -> Response:
12
"""
13
Lists the metric values for a resource.
14
15
Parameters:
16
- resource_uri: str - Resource identifier
17
- timespan: Optional[str] - Time range (ISO 8601 format)
18
- interval: Optional[str] - Metric sampling interval
19
- metricnames: Optional[str] - Comma-separated list of metric names
20
- aggregation: Optional[str] - Aggregation types to retrieve
21
- top: Optional[int] - Maximum number of records to retrieve
22
- orderby: Optional[str] - Aggregation to order results by
23
- filter: Optional[str] - OData filter for dimensions
24
- result_type: Optional[ResultType] - Result granularity (Data or Metadata)
25
- metricnamespace: Optional[str] - Metric namespace to query
26
- auto_adjust_timegrain: Optional[bool] - Auto-adjust time grain
27
- validate_dimensions: Optional[bool] - Validate dimension names and values
28
- rollupby: Optional[str] - Dimension to aggregate results by
29
30
Returns:
31
Response - Metric data response
32
"""
33
34
def list_at_subscription_scope(region: str, timespan: Optional[str] = None, interval: Optional[str] = None, metricnames: Optional[str] = None, aggregation: Optional[str] = None, top: Optional[int] = None, orderby: Optional[str] = None, filter: Optional[str] = None, result_type: Optional[MetricResultType] = None, metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, rollupby: Optional[str] = None, **kwargs: Any) -> Response:
35
"""
36
Lists metrics at subscription scope for a region.
37
38
Parameters:
39
- region: str - Azure region name
40
- timespan: Optional[str] - Time range (ISO 8601 format)
41
- interval: Optional[str] - Metric sampling interval
42
- metricnames: Optional[str] - Comma-separated list of metric names
43
- aggregation: Optional[str] - Aggregation types to retrieve
44
- top: Optional[int] - Maximum number of records to retrieve
45
- orderby: Optional[str] - Aggregation to order results by
46
- filter: Optional[str] - OData filter for dimensions
47
- result_type: Optional[MetricResultType] - Result granularity
48
- metricnamespace: Optional[str] - Metric namespace to query
49
- auto_adjust_timegrain: Optional[bool] - Auto-adjust time grain
50
- validate_dimensions: Optional[bool] - Validate dimension names and values
51
- rollupby: Optional[str] - Dimension to aggregate results by
52
53
Returns:
54
Response - Subscription-level metric data response
55
"""
56
```
57
58
### Metric Definitions
59
60
Retrieve available metric definitions and metadata for resources and subscriptions.
61
62
```python { .api }
63
def list(resource_uri: str, metricnamespace: Optional[str] = None, **kwargs: Any) -> ItemPaged[MetricDefinition]:
64
"""
65
Lists the metric definitions for the resource.
66
67
Parameters:
68
- resource_uri: str - Resource identifier
69
- metricnamespace: Optional[str] - Metric namespace to filter by
70
71
Returns:
72
ItemPaged[MetricDefinition] - Available metric definitions
73
"""
74
75
def list_at_subscription_scope(region: str, metricnamespace: Optional[str] = None, **kwargs: Any) -> ItemPaged[SubscriptionScopeMetricDefinition]:
76
"""
77
Lists metric definitions at subscription scope for a region.
78
79
Parameters:
80
- region: str - Azure region name
81
- metricnamespace: Optional[str] - Metric namespace to filter by
82
83
Returns:
84
ItemPaged[SubscriptionScopeMetricDefinition] - Subscription-level metric definitions
85
"""
86
```
87
88
### Metric Namespaces
89
90
Retrieve available metric namespaces for resources to understand metric categorization.
91
92
```python { .api }
93
def list(resource_uri: str, start_time: Optional[str] = None, **kwargs: Any) -> ItemPaged[MetricNamespace]:
94
"""
95
Lists the metric namespaces for the resource.
96
97
Parameters:
98
- resource_uri: str - Resource identifier
99
- start_time: Optional[str] - Start time for namespace availability
100
101
Returns:
102
ItemPaged[MetricNamespace] - Available metric namespaces
103
"""
104
```
105
106
### Baseline Metrics
107
108
Retrieve baseline metric values for performance comparison and anomaly detection.
109
110
```python { .api }
111
def list(resource_uri: str, metricnames: Optional[str] = None, metricnamespace: Optional[str] = None, timespan: Optional[str] = None, interval: Optional[str] = None, aggregation: Optional[str] = None, sensitivities: Optional[str] = None, result_type: Optional[ResultType] = None, **kwargs: Any) -> ItemPaged[SingleMetricBaseline]:
112
"""
113
Lists the metric baselines for a resource.
114
115
Parameters:
116
- resource_uri: str - Resource identifier
117
- metricnames: Optional[str] - Comma-separated list of metric names
118
- metricnamespace: Optional[str] - Metric namespace
119
- timespan: Optional[str] - Time range for baselines
120
- interval: Optional[str] - Baseline sampling interval
121
- aggregation: Optional[str] - Aggregation types for baselines
122
- sensitivities: Optional[str] - Sensitivity levels for baselines
123
- result_type: Optional[ResultType] - Result granularity
124
125
Returns:
126
ItemPaged[SingleMetricBaseline] - Metric baseline data
127
"""
128
```
129
130
## Usage Examples
131
132
### Querying Resource Metrics
133
134
```python
135
from datetime import datetime, timedelta
136
137
# Get CPU metrics for the last hour
138
end_time = datetime.utcnow()
139
start_time = end_time - timedelta(hours=1)
140
timespan = f"{start_time.isoformat()}Z/{end_time.isoformat()}Z"
141
142
resource_uri = f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Compute/virtualMachines/web-server"
143
144
metrics_response = client.metrics.list(
145
resource_uri=resource_uri,
146
timespan=timespan,
147
interval="PT5M", # 5-minute intervals
148
metricnames="Percentage CPU,Network In Total,Network Out Total",
149
aggregation="Average,Maximum"
150
)
151
152
# Parse the response
153
metrics_data = metrics_response.value
154
for metric in metrics_data:
155
print(f"Metric: {metric.name.value}")
156
for timeseries in metric.timeseries:
157
for data_point in timeseries.data:
158
print(f" Time: {data_point.time_stamp}, Average: {data_point.average}, Maximum: {data_point.maximum}")
159
```
160
161
### Getting Metric Definitions
162
163
```python
164
# Get available metrics for a resource
165
definitions = client.metric_definitions.list(resource_uri=resource_uri)
166
167
for definition in definitions:
168
print(f"Metric: {definition.name.value}")
169
print(f" Unit: {definition.unit}")
170
print(f" Aggregations: {[agg.value for agg in definition.supported_aggregation_types]}")
171
if definition.dimensions:
172
print(f" Dimensions: {[dim.value for dim in definition.dimensions]}")
173
print()
174
```
175
176
### Subscription-Level Metric Query
177
178
```python
179
# Query subscription-level metrics for a region
180
region = "East US"
181
subscription_metrics = client.metrics.list_at_subscription_scope(
182
region=region,
183
timespan=timespan,
184
metricnames="Virtual Machine CPU Credits Consumed",
185
aggregation="Average"
186
)
187
188
subscription_data = subscription_metrics.value
189
for metric in subscription_data:
190
print(f"Subscription Metric: {metric.name.value}")
191
for timeseries in metric.timeseries:
192
for data_point in timeseries.data:
193
print(f" Time: {data_point.time_stamp}, Value: {data_point.average}")
194
```
195
196
### Baseline Comparison
197
198
```python
199
# Get baseline data for comparison
200
baselines = client.baselines.list(
201
resource_uri=resource_uri,
202
metricnames="Percentage CPU",
203
timespan=timespan,
204
interval="PT5M",
205
aggregation="Average",
206
sensitivities="Low,Medium,High"
207
)
208
209
for baseline in baselines:
210
print(f"Baseline for: {baseline.name}")
211
for timeseries in baseline.timeseries:
212
for data_point in timeseries.data:
213
print(f" Time: {data_point.time_stamp}")
214
print(f" Low Threshold: {data_point.low_threshold}")
215
print(f" High Threshold: {data_point.high_threshold}")
216
```
217
218
### Filtering by Dimensions
219
220
```python
221
# Query metrics with dimension filtering
222
filtered_metrics = client.metrics.list(
223
resource_uri=resource_uri,
224
timespan=timespan,
225
metricnames="Requests",
226
aggregation="Total",
227
filter="HttpStatus eq '200' or HttpStatus eq '404'"
228
)
229
230
for metric in filtered_metrics.value:
231
for timeseries in metric.timeseries:
232
# Each timeseries represents a unique dimension combination
233
dimensions = {dim.name: dim.value for dim in timeseries.metadatavalues}
234
print(f"Dimensions: {dimensions}")
235
for data_point in timeseries.data:
236
print(f" Requests: {data_point.total}")
237
```
238
239
## Types
240
241
```python { .api }
242
class Metrics:
243
"""Response containing metric data."""
244
cost: Optional[int] # Query cost
245
timespan: str # Time range of the data
246
interval: Optional[str] # Sampling interval
247
value: List[Metric] # List of metrics
248
namespace: Optional[str] # Metric namespace
249
resource_region: Optional[str] # Resource region
250
251
class Metric:
252
"""Individual metric data."""
253
id: str # Metric identifier
254
type: str # Metric type
255
name: LocalizableString # Metric name
256
display_description: Optional[str] # Metric description
257
error_code: Optional[str] # Error code if applicable
258
error_message: Optional[str] # Error message if applicable
259
unit: MetricUnit # Metric unit
260
timeseries: List[TimeSeriesElement] # Time series data
261
262
class TimeSeriesElement:
263
"""Time series data for a metric."""
264
metadatavalues: Optional[List[MetadataValue]] # Dimension values
265
data: List[MetricValue] # Data points
266
267
class MetricValue:
268
"""Individual metric data point."""
269
time_stamp: datetime # Data point timestamp
270
average: Optional[float] # Average value
271
minimum: Optional[float] # Minimum value
272
maximum: Optional[float] # Maximum value
273
total: Optional[float] # Total value
274
count: Optional[int] # Count value
275
276
class MetricDefinition:
277
"""Metric definition and metadata."""
278
is_dimension_required: Optional[bool] # Whether dimensions are required
279
resource_id: Optional[str] # Resource ID
280
namespace: Optional[str] # Metric namespace
281
name: Optional[LocalizableString] # Metric name
282
display_description: Optional[str] # Metric description
283
category: Optional[str] # Metric category
284
metric_class: Optional[MetricClass] # Metric classification
285
unit: Optional[MetricUnit] # Metric unit
286
primary_aggregation_type: Optional[AggregationType] # Primary aggregation
287
supported_aggregation_types: Optional[List[AggregationType]] # Supported aggregations
288
metric_availabilities: Optional[List[MetricAvailability]] # Availability information
289
id: Optional[str] # Definition ID
290
dimensions: Optional[List[LocalizableString]] # Available dimensions
291
292
class MetricNamespace:
293
"""Metric namespace information."""
294
id: Optional[str] # Namespace ID
295
type: Optional[str] # Namespace type
296
name: Optional[str] # Namespace name
297
classification: Optional[NamespaceClassification] # Namespace classification
298
properties: Optional[MetricNamespaceName] # Namespace properties
299
300
class SingleMetricBaseline:
301
"""Baseline data for a single metric."""
302
id: str # Baseline ID
303
type: str # Baseline type
304
name: str # Baseline name
305
properties: Optional[BaselineResponse] # Baseline properties
306
307
class BaselineResponse:
308
"""Baseline response data."""
309
timespan: Optional[str] # Time range
310
interval: Optional[str] # Sampling interval
311
aggregation: Optional[str] # Aggregation type
312
timestamps: Optional[List[datetime]] # Timestamps
313
baseline: Optional[List[Baseline]] # Baseline values
314
315
class Baseline:
316
"""Baseline threshold values."""
317
sensitivity: Optional[BaselineSensitivity] # Sensitivity level
318
low_thresholds: List[float] # Low threshold values
319
high_thresholds: List[float] # High threshold values
320
321
class MetadataValue:
322
"""Metric dimension metadata."""
323
name: LocalizableString # Dimension name
324
value: Optional[str] # Dimension value
325
326
MetricUnit = Union[
327
"Count", "Bytes", "Seconds", "CountPerSecond", "BytesPerSecond",
328
"Percent", "MilliSeconds", "ByteSeconds", "Unspecified", "Cores",
329
"MilliCores", "NanoCores", "BitsPerSecond"
330
]
331
332
MetricClass = Union["Availability", "Transactions", "Errors", "Latency", "Saturation"]
333
334
BaselineSensitivity = Union["Low", "Medium", "High"]
335
336
ResultType = Union["Data", "Metadata"]
337
338
MetricResultType = Union["Data", "Metadata"]
339
```