Skip to content

Commit d4d5f6d

Browse files
authored
Merge pull request #91488 from lgayhardt/appinsightspythonsdk1019
Update docs for OpenCensus Python SDK to reflect changes for GA
2 parents 092d78a + 1bdc10d commit d4d5f6d

File tree

3 files changed

+208
-18
lines changed

3 files changed

+208
-18
lines changed
36.5 KB
Loading

articles/azure-monitor/app/opencensus-python.md

Lines changed: 206 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
11
---
2-
title: Monitor Python applications with Azure Application Insights | Microsoft Docs
3-
description: Provides instructions to wire up OpenCensus Python with Application Insights
2+
title: Monitor Python applications with Azure Monitor | Microsoft Docs
3+
description: Provides instructions to wire up OpenCensus Python with Azure Monitor
44
services: application-insights
55
keywords:
66
author: reyang
77
ms.author: reyang
8-
ms.date: 07/02/2019
8+
ms.date: 10/11/2019
99
ms.service: application-insights
1010
ms.topic: conceptual
1111
ms.reviewer: mbullwin
1212
manager: carmonm
1313
---
1414

15-
# Collect distributed traces from Python (Preview)
15+
# Set up Azure Monitor for your Python application
1616

17-
Application Insights now supports distributed tracing of Python applications through integration with [OpenCensus](https://opencensus.io). This article will walk you step-by-step through the process of setting up OpenCensus for Python and getting your monitoring data to Application Insights.
17+
Azure Monitor supports distributed tracing, metric collection and logging of Python applications through integration with [OpenCensus](https://opencensus.io). This article will walk you step-by-step through the process of setting up OpenCensus for Python and getting your monitoring data to Azure Monitor.
1818

1919
## Prerequisites
2020

2121
- You need an Azure Subscription.
22-
- Python should be installed, this article uses [Python 3.7.0](https://www.python.org/downloads/), though earlier versions will likely work with minor adjustment.
22+
- Python should be installed, this article uses [Python 3.7.0](https://www.python.org/downloads/), though earlier versions will likely work with minor adjustments.
2323

2424
If you don't have an Azure subscription, create a [free](https://azure.microsoft.com/free/) account before you begin.
2525

2626
## Sign in to the Azure portal
2727

2828
Sign in to the [Azure portal](https://portal.azure.com/).
2929

30-
## Create Application Insights resource
30+
## Create Application Insights resource in Azure Monitor
3131

32-
First you have to create an Application Insights resource, which will generate an instrumentation key(ikey). The ikey is then used to configure the OpenCensus SDK to send telemetry data to Application Insights.
32+
First you have to create an Application Insights resource in Azure Monitor, which will generate an instrumentation key(ikey). The ikey is then used to configure the OpenCensus SDK to send telemetry data to Azure Monitor.
3333

3434
1. Select **Create a resource** > **Developer Tools** > **Application Insights**.
3535

@@ -45,7 +45,7 @@ First you have to create an Application Insights resource, which will generate a
4545

4646
2. Click **Create**.
4747

48-
## Install OpenCensus Azure Monitor Exporters
48+
## Instrumenting with OpenCensus Python SDK for Azure Monitor
4949

5050
1. Install the OpenCensus Azure Monitor Exporters:
5151

@@ -56,7 +56,11 @@ First you have to create an Application Insights resource, which will generate a
5656
> [!NOTE]
5757
> `python -m pip install opencensus-ext-azure` assumes that you have a PATH environment variable set for your Python installation. If you have not configured this, you would need to give the full directory path to where your Python executable is located which would result in a command like: `C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe -m pip install opencensus-ext-azure`.
5858

59-
2. First let's generate some trace data locally. In Python IDLE, or your editor of choice, enter the following code:
59+
2. The SDK utilizes three Azure Monitor exporters to send different types of telemetry to Azure Monitor: trace, metrics, and logs. Take a look at [the data platform overview](https://docs.microsoft.com/azure/azure-monitor/platform/data-platform) for more details on these different types. Follow the instructions below to see how to send these different types via the three exporters.
60+
61+
### Trace
62+
63+
1. First let's generate some trace data locally. In Python IDLE, or your editor of choice, enter the following code.
6064

6165
```python
6266
from opencensus.trace.samplers import ProbabilitySampler
@@ -77,7 +81,7 @@ First you have to create an Application Insights resource, which will generate a
7781
main()
7882
```
7983

80-
3. Running the code will repeatedly prompt you to enter a value. With each entry, the value will be printed to the shell, and a corresponding piece of **SpanData** will be generated by the OpenCensus Python Module. The OpenCensus project defines a [_trace as a tree of spans_](https://opencensus.io/core-concepts/tracing/).
84+
2. Running the code will repeatedly prompt you to enter a value. With each entry, the value will be printed to the shell, and a corresponding piece of **SpanData** will be generated by the OpenCensus Python Module. The OpenCensus project defines a [_trace as a tree of spans_](https://opencensus.io/core-concepts/tracing/).
8185
8286
```
8387
Enter a value: 4
@@ -91,7 +95,7 @@ First you have to create an Application Insights resource, which will generate a
9195
[SpanData(name='test', context=SpanContext(trace_id=8aa41bc469f1a705aed1bdb20c342603, span_id=None, trace_options=TraceOptions(enabled=True), tracestate=None), span_id='f3f9f9ee6db4740a', parent_span_id=None, attributes=BoundedDict({}, maxlen=32), start_time='2019-06-27T18:21:46.157732Z', end_time='2019-06-27T18:21:47.269583Z', child_span_count=0, stack_trace=None, annotations=BoundedList([], maxlen=32), message_events=BoundedList([], maxlen=128), links=BoundedList([], maxlen=32), status=None, same_process_as_parent_span=None, span_kind=0)]
9296
```
9397

94-
4. While helpful for demonstration purposes, ultimately we want to emit the SpanData to Application Insights. Modify your code from the previous step based on the following code sample:
98+
3. While helpful for demonstration purposes, ultimately we want to emit the `SpanData` to Azure Monitor. Modify your code from the previous step based on the following code sample:
9599

96100
```python
97101
from opencensus.ext.azure.trace_exporter import AzureExporter
@@ -101,7 +105,7 @@ First you have to create an Application Insights resource, which will generate a
101105
# TODO: replace the all-zero GUID with your instrumentation key.
102106
tracer = Tracer(
103107
exporter=AzureExporter(
104-
instrumentation_key='00000000-0000-0000-0000-000000000000',
108+
connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000'),
105109
),
106110
sampler=ProbabilitySampler(1.0),
107111
)
@@ -118,7 +122,172 @@ First you have to create an Application Insights resource, which will generate a
118122
if __name__ == "__main__":
119123
main()
120124
```
121-
5. Now when you run the Python script, you should still be prompted to enter values, but now only the value is being printed in the shell.
125+
126+
4. Now when you run the Python script, you should still be prompted to enter values, but now only the value is being printed in the shell. The `SpanData` created will be sent to Azure Monitor. You can find the emitted span data under `dependencies`.
127+
128+
### Metrics
129+
130+
1. First, let's generate some local metric data. We will create a simple metric to track the number of times the user presses enter.
131+
132+
```python
133+
from datetime import datetime
134+
from opencensus.stats import aggregation as aggregation_module
135+
from opencensus.stats import measure as measure_module
136+
from opencensus.stats import stats as stats_module
137+
from opencensus.stats import view as view_module
138+
from opencensus.tags import tag_map as tag_map_module
139+
140+
stats = stats_module.stats
141+
view_manager = stats.view_manager
142+
stats_recorder = stats.stats_recorder
143+
144+
prompt_measure = measure_module.MeasureInt("prompts",
145+
"number of prompts",
146+
"prompts")
147+
prompt_view = view_module.View("prompt view",
148+
"number of prompts",
149+
[],
150+
prompt_measure,
151+
aggregation_module.CountAggregation())
152+
view_manager.register_view(prompt_view)
153+
mmap = stats_recorder.new_measurement_map()
154+
tmap = tag_map_module.TagMap()
155+
156+
def prompt():
157+
input("Press enter.")
158+
mmap.measure_int_put(prompt_measure, 1)
159+
mmap.record(tmap)
160+
metrics = list(mmap.measure_to_view_map.get_metrics(datetime.utcnow()))
161+
print(metrics[0].time_series[0].points[0])
162+
163+
def main():
164+
while True:
165+
prompt()
166+
167+
if __name__ == "__main__":
168+
main()
169+
```
170+
2. Running the code will repeatedly prompt you to press enter. A metric is created to track the number of enters pressed. With each entry, the value will be incremented and the metric information will be displayed in the console, with the current value and the current timestamp when the metric was updated.
171+
172+
```
173+
Press enter.
174+
Point(value=ValueLong(5), timestamp=2019-10-09 20:58:04.930426)
175+
Press enter.
176+
Point(value=ValueLong(6), timestamp=2019-10-09 20:58:06.570167)
177+
Press enter.
178+
Point(value=ValueLong(7), timestamp=2019-10-09 20:58:07.138614)
179+
```
180+
181+
3. While helpful for demonstration purposes, ultimately we want to emit the metric data to Azure Monitor. Modify your code from the previous step based on the following code sample:
182+
183+
```python
184+
from datetime import datetime
185+
from opencensus.ext.azure import metrics_exporter
186+
from opencensus.stats import aggregation as aggregation_module
187+
from opencensus.stats import measure as measure_module
188+
from opencensus.stats import stats as stats_module
189+
from opencensus.stats import view as view_module
190+
from opencensus.tags import tag_map as tag_map_module
191+
192+
stats = stats_module.stats
193+
view_manager = stats.view_manager
194+
stats_recorder = stats.stats_recorder
195+
196+
prompt_measure = measure_module.MeasureInt("prompts",
197+
"number of prompts",
198+
"prompts")
199+
prompt_view = view_module.View("prompt view",
200+
"number of prompts",
201+
[],
202+
prompt_measure,
203+
aggregation_module.CountAggregation())
204+
view_manager.register_view(prompt_view)
205+
mmap = stats_recorder.new_measurement_map()
206+
tmap = tag_map_module.TagMap()
207+
208+
# TODO: replace the all-zero GUID with your instrumentation key.
209+
exporter = metrics_exporter.new_metrics_exporter(
210+
connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
211+
)
212+
view_manager.register_exporter(exporter)
213+
214+
def prompt():
215+
input("Press enter.")
216+
mmap.measure_int_put(prompt_measure, 1)
217+
mmap.record(tmap)
218+
metrics = list(mmap.measure_to_view_map.get_metrics(datetime.utcnow()))
219+
print(metrics[0].time_series[0].points[0])
220+
221+
def main():
222+
while True:
223+
prompt()
224+
225+
if __name__ == "__main__":
226+
main()
227+
```
228+
229+
4. The exporter will send metric data to Azure Monitor at a fixed interval, the default being every 15 seconds. We are tracking a single metric so this metric data, with whatever value and timestamp it contains, will be sent every interval. You can find the data under `customMetrics`.
230+
231+
### Logs
232+
233+
1. First, let's generate some local log data.
234+
235+
```python
236+
import logging
237+
238+
logger = logging.getLogger(__name__)
239+
240+
def valuePrompt():
241+
line = input("Enter a value: ")
242+
logger.warning(line)
243+
244+
def main():
245+
while True:
246+
valuePrompt()
247+
248+
if __name__ == "__main__":
249+
main()
250+
```
251+
252+
2. The code will ask continuously prompt for a value to be entered. A log entry is emitted for every value that is entered containing the said value.
253+
254+
```
255+
Enter a value: 24
256+
24
257+
Enter a value: 55
258+
55
259+
Enter a value: 123
260+
123
261+
Enter a value: 90
262+
90
263+
```
264+
265+
3. While helpful for demonstration purposes, ultimately we want to emit the metric data to Azure Monitor. Modify your code from the previous step based on the following code sample:
266+
267+
```python
268+
import logging
269+
from opencensus.ext.azure.log_exporter import AzureLogHandler
270+
271+
logger = logging.getLogger(__name__)
272+
273+
# TODO: replace the all-zero GUID with your instrumentation key.
274+
logger.addHandler(AzureLogHandler(
275+
connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
276+
)
277+
278+
def valuePrompt():
279+
line = input("Enter a value: ")
280+
logger.warning(line)
281+
282+
def main():
283+
while True:
284+
valuePrompt()
285+
286+
if __name__ == "__main__":
287+
main()
288+
```
289+
290+
4. The exporter will send log data to Azure Monitor. You can find the data under `traces`.
122291

123292
## Start monitoring in the Azure portal
124293

@@ -142,8 +311,23 @@ First you have to create an Application Insights resource, which will generate a
142311

143312
![Screenshot of end-to-end transaction interface](./media/opencensus-python/0009-end-to-end-transaction.png)
144313

314+
## View your data with queries
315+
316+
1. You can view the telemetry data that was sent from your application through the Logs(Analytics) tab.
317+
318+
![Screenshot of overview pane with Logs(Analytics) selected in red box](./media/opencensus-python/0010-logs-query.png)
319+
320+
2. For telemetry sent with the Azure Monitor trace exporter, incoming requests will show up under `requests` and out-going/in process requests will show up under `dependencies`.
321+
322+
3. For telemetry sent with the Azure Monitor metrics exporter, metrics sent will show up under `customMetrics`.
323+
324+
4. For telemetry sent with the Azure Monitor logs exporter, logs will show up under `traces` and exceptions will show up under `exceptions`.
325+
326+
5. Take a look at [Logs in Azure Monitor](https://docs.microsoft.com/azure/azure-monitor/platform/data-platform-logs) for more detailed information about how to use queries and logs.
327+
145328
## OpenCensus for Python
146329

330+
* [OpenCensus Python on GitHub](https://github.com/census-instrumentation/opencensus-python)
147331
* [Customization](https://github.com/census-instrumentation/opencensus-python/blob/master/README.rst#customization)
148332
* [Flask Integration](https://github.com/census-instrumentation/opencensus-python/tree/master/contrib/opencensus-ext-flask)
149333
* [Django Integration](https://github.com/census-instrumentation/opencensus-python/tree/master/contrib/opencensus-ext-django)
@@ -152,6 +336,12 @@ First you have to create an Application Insights resource, which will generate a
152336

153337
## Next steps
154338

155-
* [OpenCensus Python on GitHub](https://github.com/census-instrumentation/opencensus-python)
339+
* [API Summary](./../../azure-monitor/app/api-custom-events-metrics.md)
156340
* [Application map](./../../azure-monitor/app/app-map.md)
157-
* [End-to-end performance monitoring](./../../azure-monitor/learn/tutorial-performance.md)
341+
* [End-to-end performance monitoring](./../../azure-monitor/learn/tutorial-performance.md)
342+
343+
### Alerts
344+
345+
* [Availability tests](../../azure-monitor/app/monitor-web-app-availability.md): Create tests to make sure your site is visible on the web.
346+
* [Smart diagnostics](../../azure-monitor/app/proactive-diagnostics.md): These tests run automatically, so you don't have to do anything to set them up. They tell you if your app has an unusual rate of failed requests.
347+
* [Metric alerts](../../azure-monitor/app/alerts.md): Set alerts to warn you if a metric crosses a threshold. You can set them on custom metrics that you code into your app.

articles/azure-monitor/toc.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,8 @@
206206
items:
207207
- name: Node.js
208208
href: app/nodejs.md
209+
- name: Python
210+
href: app/opencensus-python.md
209211
- name: Web pages
210212
items:
211213
- name: Client-side JavaScript
@@ -300,8 +302,6 @@
300302
displayname: correlation headers, w3c, distributed tracing, tracing
301303
- name: Local forwarder
302304
href: app/opencensus-local-forwarder.md
303-
- name: Python
304-
href: app/opencensus-python.md
305305
- name: Go
306306
href: app/opencensus-go.md
307307
- name: Live Metric stream

0 commit comments

Comments
 (0)