0
# Monitoring and Analytics
1
2
Azure monitoring and analytics services provide application performance monitoring, log analytics, and operational insights. This includes Application Insights for application performance monitoring and Log Analytics for log data analysis and visualization.
3
4
## Capabilities
5
6
### Azure Application Insights
7
8
Provides application performance monitoring and analytics for web applications and services. Collects telemetry data including requests, dependencies, exceptions, and custom metrics.
9
10
```python { .api }
11
class ApplicationInsightsDataClient:
12
"""
13
Client for Application Insights Data API operations.
14
15
Parameters:
16
- credentials: Authentication credentials
17
"""
18
def __init__(self, credentials, **kwargs): ...
19
20
@property
21
def query(self): ... # Query operations
22
23
@property
24
def metrics(self): ... # Metrics operations
25
26
@property
27
def events(self): ... # Events operations
28
```
29
30
#### Query Operations
31
32
Execute KQL (Kusto Query Language) queries against Application Insights data.
33
34
```python { .api }
35
class QueryOperations:
36
def execute(self, app_id: str, body, **kwargs):
37
"""
38
Execute a KQL query against Application Insights data.
39
40
Parameters:
41
- app_id: str, Application Insights application ID
42
- body: QueryBody, Query request body containing KQL query
43
44
Returns:
45
QueryResults object with query results
46
"""
47
```
48
49
#### Metrics Operations
50
51
Retrieve pre-aggregated metrics from Application Insights applications.
52
53
```python { .api }
54
class MetricsOperations:
55
def get(self, app_id: str, metric_id: str, **kwargs):
56
"""
57
Get a specific metric from an Application Insights application.
58
59
Parameters:
60
- app_id: str, Application Insights application ID
61
- metric_id: str, Metric identifier
62
63
Returns:
64
MetricsResult object with metric data
65
"""
66
67
def get_multiple(self, app_id: str, body, **kwargs):
68
"""
69
Get multiple metrics from an Application Insights application.
70
71
Parameters:
72
- app_id: str, Application Insights application ID
73
- body: MetricsPostBody, Request body with metric specifications
74
75
Returns:
76
List of MetricsResult objects
77
"""
78
```
79
80
#### Events Operations
81
82
Retrieve event data from Application Insights applications.
83
84
```python { .api }
85
class EventsOperations:
86
def get_by_type(self, app_id: str, event_type: str, event_id: str, **kwargs):
87
"""
88
Get a specific event by type and ID.
89
90
Parameters:
91
- app_id: str, Application Insights application ID
92
- event_type: str, Event type (requests, dependencies, exceptions, etc.)
93
- event_id: str, Event identifier
94
95
Returns:
96
EventsResult object with event data
97
"""
98
99
def get(self, app_id: str, event_type: str, **kwargs):
100
"""
101
Get events of a specific type.
102
103
Parameters:
104
- app_id: str, Application Insights application ID
105
- event_type: str, Event type to retrieve
106
107
Returns:
108
EventsResults object with events data
109
"""
110
```
111
112
### Azure Log Analytics
113
114
Provides log data collection, analysis, and visualization capabilities. Supports KQL queries for advanced log analysis and custom dashboards.
115
116
```python { .api }
117
class LogAnalyticsDataClient:
118
"""
119
Client for Azure Log Analytics Data API operations.
120
121
Parameters:
122
- credentials: Authentication credentials
123
"""
124
def __init__(self, credentials, **kwargs): ...
125
126
@property
127
def query(self): ... # Query operations
128
```
129
130
#### Log Analytics Query Operations
131
132
Execute KQL queries against Log Analytics workspaces.
133
134
```python { .api }
135
class QueryOperations:
136
def execute(self, workspace_id: str, body, **kwargs):
137
"""
138
Execute a KQL query against a Log Analytics workspace.
139
140
Parameters:
141
- workspace_id: str, Log Analytics workspace ID
142
- body: QueryBody, Query request body with KQL query
143
144
Returns:
145
QueryResults object with query results
146
"""
147
```
148
149
## Data Models
150
151
### Application Insights Models
152
153
```python { .api }
154
class QueryBody:
155
"""Request body for Application Insights queries."""
156
def __init__(self, query: str, **kwargs): ...
157
158
query: str # KQL query string
159
timespan: str # Time range for the query (optional, ISO 8601 duration)
160
applications: list # Additional application IDs to include (optional)
161
162
class QueryResults:
163
"""Results from an Application Insights query."""
164
def __init__(self): ...
165
166
tables: list # Result tables
167
error: object # Error information if query failed
168
169
class QueryResultsTable:
170
"""Individual table from query results."""
171
def __init__(self): ...
172
173
name: str # Table name
174
columns: list # Column definitions
175
rows: list # Data rows
176
177
class Column:
178
"""Column definition in query results."""
179
def __init__(self): ...
180
181
name: str # Column name
182
type: str # Column data type (string, datetime, long, real, etc.)
183
184
class MetricsPostBody:
185
"""Request body for retrieving multiple metrics."""
186
def __init__(self, metrics: list, **kwargs): ...
187
188
metrics: list # List of metric specifications
189
timespan: str # Time range (optional)
190
interval: str # Aggregation interval (optional)
191
aggregation: list # Aggregation types (optional)
192
segment: list # Segmentation dimensions (optional)
193
top: int # Top N results (optional)
194
orderby: str # Sort order (optional)
195
filter: str # Filter expression (optional)
196
197
class MetricsResult:
198
"""Result from a metrics query."""
199
def __init__(self): ...
200
201
value: object # Metric value data
202
start: str # Start time of the metric period
203
end: str # End time of the metric period
204
205
class EventsResults:
206
"""Results from an events query."""
207
def __init__(self): ...
208
209
value: list # List of events
210
ai_messages: list # AI-generated insights (optional)
211
212
class EventsResult:
213
"""Individual event result."""
214
def __init__(self): ...
215
216
id: str # Event identifier
217
count: int # Event occurrence count
218
timestamp: str # Event timestamp
219
customDimensions: dict # Custom properties
220
customMeasurements: dict # Custom measurements
221
```
222
223
### Log Analytics Models
224
225
```python { .api }
226
class QueryBody:
227
"""Request body for Log Analytics queries."""
228
def __init__(self, query: str, **kwargs): ...
229
230
query: str # KQL query string
231
timespan: str # Time range for the query (optional)
232
workspaces: list # Additional workspace IDs to query (optional)
233
234
class QueryResults:
235
"""Results from a Log Analytics query."""
236
def __init__(self): ...
237
238
tables: list # Result tables
239
error: object # Error information if query failed
240
241
class ErrorInfo:
242
"""Error information for failed queries."""
243
def __init__(self): ...
244
245
code: str # Error code
246
message: str # Error message
247
details: list # Additional error details
248
```
249
250
## Usage Examples
251
252
### Querying Application Insights Data
253
254
```python
255
from azure.applicationinsights import ApplicationInsightsDataClient
256
from azure.applicationinsights.models import QueryBody
257
258
# Create Application Insights client
259
ai_client = ApplicationInsightsDataClient(credentials)
260
261
# Application ID from Application Insights
262
app_id = "12345678-1234-1234-1234-123456789abc"
263
264
# Execute a KQL query
265
query_body = QueryBody(
266
query="""
267
requests
268
| where timestamp > ago(24h)
269
| summarize count() by bin(timestamp, 1h), resultCode
270
| order by timestamp desc
271
""",
272
timespan="P1D" # Last 1 day
273
)
274
275
results = ai_client.query.execute(app_id, query_body)
276
277
# Process results
278
for table in results.tables:
279
print(f"Table: {table.name}")
280
print("Columns:", [col.name for col in table.columns])
281
282
for row in table.rows:
283
print("Row:", row)
284
285
# Query for exceptions
286
exception_query = QueryBody(
287
query="""
288
exceptions
289
| where timestamp > ago(1h)
290
| project timestamp, type, outerMessage, operation_Name
291
| order by timestamp desc
292
| take 10
293
"""
294
)
295
296
exception_results = ai_client.query.execute(app_id, exception_query)
297
print(f"Found {len(exception_results.tables[0].rows)} exceptions in the last hour")
298
```
299
300
### Retrieving Application Insights Metrics
301
302
```python
303
from azure.applicationinsights.models import MetricsPostBody
304
305
# Get request rate metric
306
request_metric = ai_client.metrics.get(
307
app_id=app_id,
308
metric_id="requests/rate"
309
)
310
311
print(f"Request rate: {request_metric.value}")
312
313
# Get multiple metrics
314
metrics_body = MetricsPostBody(
315
metrics=[
316
{"id": "requests/rate"},
317
{"id": "requests/duration"},
318
{"id": "exceptions/rate"}
319
],
320
timespan="PT1H", # Last 1 hour
321
interval="PT5M" # 5-minute intervals
322
)
323
324
multiple_metrics = ai_client.metrics.get_multiple(app_id, metrics_body)
325
326
for metric in multiple_metrics:
327
print(f"Metric: {metric.value}")
328
```
329
330
### Working with Application Insights Events
331
332
```python
333
# Get recent requests
334
requests = ai_client.events.get(
335
app_id=app_id,
336
event_type="requests"
337
)
338
339
print(f"Found {len(requests.value)} requests")
340
341
for request in requests.value[:5]: # Show first 5
342
print(f"Request: {request.id}")
343
print(f"Timestamp: {request.timestamp}")
344
print(f"Custom dimensions: {request.customDimensions}")
345
346
# Get a specific event
347
specific_event = ai_client.events.get_by_type(
348
app_id=app_id,
349
event_type="requests",
350
event_id="some-request-id"
351
)
352
353
print(f"Event details: {specific_event.id}")
354
```
355
356
### Querying Log Analytics Data
357
358
```python
359
from azure.loganalytics import LogAnalyticsDataClient
360
from azure.loganalytics.models import QueryBody
361
362
# Create Log Analytics client
363
la_client = LogAnalyticsDataClient(credentials)
364
365
# Workspace ID from Log Analytics
366
workspace_id = "12345678-1234-1234-1234-123456789abc"
367
368
# Execute a KQL query
369
query_body = QueryBody(
370
query="""
371
Heartbeat
372
| where TimeGenerated > ago(1h)
373
| summarize count() by Computer, bin(TimeGenerated, 5m)
374
| order by TimeGenerated desc
375
""",
376
timespan="PT1H"
377
)
378
379
results = la_client.query.execute(workspace_id, query_body)
380
381
# Process results
382
if results.tables:
383
table = results.tables[0]
384
print(f"Query returned {len(table.rows)} rows")
385
386
# Print column headers
387
headers = [col.name for col in table.columns]
388
print("Columns:", headers)
389
390
# Print first few rows
391
for row in table.rows[:10]:
392
print("Row:", dict(zip(headers, row)))
393
394
# Query for security events
395
security_query = QueryBody(
396
query="""
397
SecurityEvent
398
| where TimeGenerated > ago(24h)
399
| where EventID == 4625 // Failed logon attempts
400
| summarize FailedAttempts = count() by Account, IpAddress
401
| where FailedAttempts > 5
402
| order by FailedAttempts desc
403
"""
404
)
405
406
security_results = la_client.query.execute(workspace_id, security_query)
407
print(f"Found {len(security_results.tables[0].rows)} accounts with multiple failed logons")
408
```
409
410
### Error Handling
411
412
```python
413
from azure.applicationinsights.models import QueryBody
414
415
try:
416
# Execute query with syntax error
417
bad_query = QueryBody(query="invalid KQL syntax")
418
results = ai_client.query.execute(app_id, bad_query)
419
420
if results.error:
421
print(f"Query error: {results.error.message}")
422
print(f"Error code: {results.error.code}")
423
424
except Exception as e:
425
print(f"Request failed: {e}")
426
427
# Check for empty results
428
query_body = QueryBody(
429
query="requests | where timestamp > ago(1d) | take 0"
430
)
431
432
results = ai_client.query.execute(app_id, query_body)
433
434
if not results.tables or not results.tables[0].rows:
435
print("No data found for the specified time range")
436
else:
437
print(f"Found {len(results.tables[0].rows)} results")
438
```
439
440
### Advanced KQL Queries
441
442
```python
443
# Performance analysis query
444
perf_query = QueryBody(
445
query="""
446
requests
447
| where timestamp > ago(24h)
448
| join (dependencies | where timestamp > ago(24h)) on operation_Id
449
| project
450
timestamp,
451
name,
452
duration,
453
dependency_duration = duration1,
454
dependency_name = name1,
455
success,
456
resultCode
457
| where duration > 1000 // Slow requests (>1 second)
458
| order by duration desc
459
| take 20
460
"""
461
)
462
463
perf_results = ai_client.query.execute(app_id, perf_query)
464
465
# User behavior analysis
466
user_query = QueryBody(
467
query="""
468
pageViews
469
| where timestamp > ago(7d)
470
| extend hour = bin(timestamp, 1h)
471
| summarize
472
UniqueUsers = dcount(user_Id),
473
PageViews = count(),
474
AvgDuration = avg(duration)
475
by hour
476
| order by hour desc
477
"""
478
)
479
480
user_results = ai_client.query.execute(app_id, user_query)
481
```