Skip to content

Commit db1d47f

Browse files
committed
add metrics exporter example
1 parent 549f61f commit db1d47f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

articles/azure-monitor/app/api-filtering-sampling.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,59 @@ tracer = Tracer(exporter=exporter, sampler=ProbabilitySampler(1.0))
422422
with tracer.span(name='parent'):
423423
response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')
424424
```
425+
426+
```python
427+
# Example for metrics exporter
428+
import time
429+
430+
from opencensus.ext.azure import metrics_exporter
431+
from opencensus.stats import aggregation as aggregation_module
432+
from opencensus.stats import measure as measure_module
433+
from opencensus.stats import stats as stats_module
434+
from opencensus.stats import view as view_module
435+
from opencensus.tags import tag_map as tag_map_module
436+
437+
stats = stats_module.stats
438+
view_manager = stats.view_manager
439+
stats_recorder = stats.stats_recorder
440+
441+
CARROTS_MEASURE = measure_module.MeasureInt("carrots",
442+
"number of carrots",
443+
"carrots")
444+
CARROTS_VIEW = view_module.View("carrots_view",
445+
"number of carrots",
446+
[],
447+
CARROTS_MEASURE,
448+
aggregation_module.CountAggregation())
449+
450+
# Callback function to only export the metric if value is greater than 0
451+
def callback_function(envelope):
452+
return envelope.data.baseData.metrics[0].value > 0
453+
454+
def main():
455+
# Enable metrics
456+
# Set the interval in seconds in which you want to send metrics
457+
exporter = metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>')
458+
exporter.add_telemetry_processor(callback_function)
459+
view_manager.register_exporter(exporter)
460+
461+
view_manager.register_view(CARROTS_VIEW)
462+
mmap = stats_recorder.new_measurement_map()
463+
tmap = tag_map_module.TagMap()
464+
465+
mmap.measure_int_put(CARROTS_MEASURE, 1000)
466+
mmap.record(tmap)
467+
# Default export interval is every 15.0s
468+
# Your application should run for at least this amount
469+
# of time so the exporter will meet this interval
470+
# Sleep can fulfill this
471+
time.sleep(60)
472+
473+
print("Done recording metrics")
474+
475+
if __name__ == "__main__":
476+
main()
477+
```
425478
You can add as many processors as you like, and they are called in the order they are added. If one processor should throw an exception, it does not impact the following processors.
426479

427480
### Example TelemetryInitializers

0 commit comments

Comments
 (0)